Unverified Commit d9e3803e authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix server references handling in the edge runtime (#48502)

Currently POST requests to `"use server"` entries are not correctly
handled, and this PR partially fixes the behavior. Note that the
`isMultipartAction` case is still missing as we can't simply use
`busboy`. Later we'll unify the implementation here to always use
FormData via Undici.

Fixes NEXT-1026.
parent 1c677406
...@@ -1261,8 +1261,13 @@ export default async function build( ...@@ -1261,8 +1261,13 @@ export default async function build(
: null : null
const entriesWithAction = actionManifest ? new Set() : null const entriesWithAction = actionManifest ? new Set() : null
if (actionManifest && entriesWithAction) { if (actionManifest && entriesWithAction) {
for (const id in actionManifest) { for (const id in actionManifest.node) {
for (const entry in actionManifest[id].workers) { for (const entry in actionManifest.node[id].workers) {
entriesWithAction.add(entry)
}
}
for (const id in actionManifest.edge) {
for (const entry in actionManifest.edge[id].workers) {
entriesWithAction.add(entry) entriesWithAction.add(entry)
} }
} }
......
...@@ -44,18 +44,21 @@ interface Options { ...@@ -44,18 +44,21 @@ interface Options {
const PLUGIN_NAME = 'ClientEntryPlugin' const PLUGIN_NAME = 'ClientEntryPlugin'
export type ActionManifest = { export type ActionManifest = {
[actionId: string]: { [key in 'node' | 'edge']: {
workers: { [actionId: string]: {
[name: string]: string | number workers: {
[name: string]: string | number
}
} }
} }
} }
const pluginState = getProxiedPluginState({ const pluginState = getProxiedPluginState({
// A map to track "action" -> "list of bundles". // A map to track "action" -> "list of bundles".
serverActions: {} as ActionManifest, serverActions: {} as ActionManifest['node'],
edgeServerActions: {} as ActionManifest, edgeServerActions: {} as ActionManifest['edge'],
actionModId: {} as Record<string, string | number>, actionModServerId: {} as Record<string, string | number>,
actionModEdgeServerId: {} as Record<string, string | number>,
// Manifest of CSS entry files for server/edge server. // Manifest of CSS entry files for server/edge server.
serverCSSManifest: {} as ClientCSSReferenceManifest, serverCSSManifest: {} as ClientCSSReferenceManifest,
...@@ -78,12 +81,14 @@ export class ClientReferenceEntryPlugin { ...@@ -78,12 +81,14 @@ export class ClientReferenceEntryPlugin {
appDir: string appDir: string
isEdgeServer: boolean isEdgeServer: boolean
useExperimentalReact: boolean useExperimentalReact: boolean
assetPrefix: string
constructor(options: Options) { constructor(options: Options) {
this.dev = options.dev this.dev = options.dev
this.appDir = options.appDir this.appDir = options.appDir
this.isEdgeServer = options.isEdgeServer this.isEdgeServer = options.isEdgeServer
this.useExperimentalReact = options.useExperimentalReact this.useExperimentalReact = options.useExperimentalReact
this.assetPrefix = !this.dev && !this.isEdgeServer ? '../' : ''
} }
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
...@@ -152,8 +157,6 @@ export class ClientReferenceEntryPlugin { ...@@ -152,8 +157,6 @@ export class ClientReferenceEntryPlugin {
compilation.hooks.processAssets.tap( compilation.hooks.processAssets.tap(
{ {
name: PLUGIN_NAME, name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
}, },
(assets) => this.createAsset(compilation, assets) (assets) => this.createAsset(compilation, assets)
...@@ -237,13 +240,6 @@ export class ClientReferenceEntryPlugin { ...@@ -237,13 +240,6 @@ export class ClientReferenceEntryPlugin {
}) })
) )
// Create action entry
if (this.isEdgeServer) {
pluginState.edgeServerActions = {}
} else {
pluginState.serverActions = {}
}
if (actionEntryImports.size > 0) { if (actionEntryImports.size > 0) {
if (!this.useExperimentalReact) { if (!this.useExperimentalReact) {
warnOnce( warnOnce(
...@@ -424,8 +420,6 @@ export class ClientReferenceEntryPlugin { ...@@ -424,8 +420,6 @@ export class ClientReferenceEntryPlugin {
compilation.hooks.processAssets.tap( compilation.hooks.processAssets.tap(
{ {
name: PLUGIN_NAME, name: PLUGIN_NAME,
// Have to be in the optimize stage to run after updating the CSS
// asset hash via extract mini css plugin.
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
}, },
(assets: webpack.Compilation['assets']) => { (assets: webpack.Compilation['assets']) => {
...@@ -440,12 +434,14 @@ export class ClientReferenceEntryPlugin { ...@@ -440,12 +434,14 @@ export class ClientReferenceEntryPlugin {
}, },
} }
const manifest = JSON.stringify(data, null, this.dev ? 2 : undefined) const manifest = JSON.stringify(data, null, this.dev ? 2 : undefined)
assets[FLIGHT_SERVER_CSS_MANIFEST + '.json'] = new sources.RawSource( assets[`${this.assetPrefix}${FLIGHT_SERVER_CSS_MANIFEST}.json`] =
manifest new sources.RawSource(
) as unknown as webpack.sources.RawSource manifest
assets[FLIGHT_SERVER_CSS_MANIFEST + '.js'] = new sources.RawSource( ) as unknown as webpack.sources.RawSource
'self.__RSC_CSS_MANIFEST=' + manifest assets[`${this.assetPrefix}${FLIGHT_SERVER_CSS_MANIFEST}.js`] =
) as unknown as webpack.sources.RawSource new sources.RawSource(
'self.__RSC_CSS_MANIFEST=' + manifest
) as unknown as webpack.sources.RawSource
} }
) )
...@@ -723,9 +719,9 @@ export class ClientReferenceEntryPlugin { ...@@ -723,9 +719,9 @@ export class ClientReferenceEntryPlugin {
actions: JSON.stringify(actionsArray), actions: JSON.stringify(actionsArray),
})}!` })}!`
let currentCompilerServerActions = this.isEdgeServer const currentCompilerServerActions = this.isEdgeServer
? pluginState.serverActions ? pluginState.edgeServerActions
: pluginState.edgeServerActions : pluginState.serverActions
for (const [p, names] of actionsArray) { for (const [p, names] of actionsArray) {
for (const name of names) { for (const name of names) {
const id = generateActionId(p, name) const id = generateActionId(p, name)
...@@ -795,31 +791,46 @@ export class ClientReferenceEntryPlugin { ...@@ -795,31 +791,46 @@ export class ClientReferenceEntryPlugin {
mod.request && mod.request &&
/next-flight-action-entry-loader/.test(mod.request) /next-flight-action-entry-loader/.test(mod.request)
) { ) {
pluginState.actionModId[chunkGroup.name] = modId if (this.isEdgeServer) {
pluginState.actionModEdgeServerId[chunkGroup.name] = modId
} else {
pluginState.actionModServerId[chunkGroup.name] = modId
}
} }
}) })
const fullServerActions = { const serverActions: ActionManifest['node'] = {}
...pluginState.serverActions, for (let id in pluginState.serverActions) {
...pluginState.edgeServerActions, const action = pluginState.serverActions[id]
for (let name in action.workers) {
action.workers[name] = pluginState.actionModServerId[name]
}
serverActions[id] = action
} }
for (let id in fullServerActions) {
const action = fullServerActions[id] const edgeServerActions: ActionManifest['edge'] = {}
for (let id in pluginState.edgeServerActions) {
const action = pluginState.edgeServerActions[id]
for (let name in action.workers) { for (let name in action.workers) {
action.workers[name] = pluginState.actionModId[name] action.workers[name] = pluginState.actionModEdgeServerId[name]
} }
edgeServerActions[id] = action
} }
const json = JSON.stringify( const json = JSON.stringify(
fullServerActions, {
node: serverActions,
edge: edgeServerActions,
},
null, null,
this.dev ? 2 : undefined this.dev ? 2 : undefined
) )
assets[SERVER_REFERENCE_MANIFEST + '.js'] = new sources.RawSource(
'self.__RSC_SERVER_MANIFEST=' + json assets[`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.js`] =
) as unknown as webpack.sources.RawSource new sources.RawSource(
assets[SERVER_REFERENCE_MANIFEST + '.json'] = new sources.RawSource( 'self.__RSC_SERVER_MANIFEST=' + json
json ) as unknown as webpack.sources.RawSource
) as unknown as webpack.sources.RawSource assets[`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.json`] =
new sources.RawSource(json) as unknown as webpack.sources.RawSource
} }
} }
...@@ -35,13 +35,47 @@ export async function handleAction({ ...@@ -35,13 +35,47 @@ export async function handleAction({
req.method === 'POST' req.method === 'POST'
if (isFetchAction || isFormAction || isMultipartAction) { if (isFetchAction || isFormAction || isMultipartAction) {
if (process.env.NEXT_RUNTIME !== 'edge') { let bound = []
try {
let bound = []
const workerName = 'app' + pathname const workerName = 'app' + pathname
const { decodeReply } = ComponentMod const { decodeReply } = ComponentMod
try {
if (process.env.NEXT_RUNTIME === 'edge') {
const webRequest = req as unknown as Request
if (!webRequest.body) {
throw new Error('invariant: Missing request body.')
}
if (isMultipartAction) {
throw new Error('invariant: Multipart form data is not supported.')
} else {
let actionData = ''
const reader = webRequest.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
actionData += new TextDecoder().decode(value)
}
if (isFormAction) {
const formData = new URLSearchParams(actionData)
actionId = formData.get('$$id') as string
if (!actionId) {
throw new Error('Invariant: missing action ID.')
}
formData.delete('$$id')
bound = [formData]
} else {
bound = await decodeReply(actionData)
}
}
} else {
if (isMultipartAction) { if (isMultipartAction) {
const formFields: any[] = [] const formFields: any[] = []
...@@ -68,7 +102,7 @@ export async function handleAction({ ...@@ -68,7 +102,7 @@ export async function handleAction({
{ {
get: (_, id: string) => { get: (_, id: string) => {
return { return {
id: serverActionsManifest[id].workers[workerName], id: serverActionsManifest.node[id].workers[workerName],
name: id, name: id,
chunks: [], chunks: [],
} }
...@@ -93,45 +127,46 @@ export async function handleAction({ ...@@ -93,45 +127,46 @@ export async function handleAction({
bound = await decodeReply(actionData) bound = await decodeReply(actionData)
} }
} }
}
const actionModId = serverActionsManifest[actionId].workers[workerName] const actionModId =
const actionHandler = serverActionsManifest[
ComponentMod.__next_app_webpack_require__(actionModId)[actionId] process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'
][actionId].workers[workerName]
const actionHandler =
ComponentMod.__next_app_webpack_require__(actionModId)[actionId]
const returnVal = await actionHandler.apply(null, bound) const returnVal = await actionHandler.apply(null, bound)
const result = new ActionRenderResult(JSON.stringify([returnVal])) const result = new ActionRenderResult(JSON.stringify([returnVal]))
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { if (isFetchAction) {
return result return result
} }
} catch (err) { } catch (err) {
if (isRedirectError(err)) { if (isRedirectError(err)) {
if (isFetchAction) { if (isFetchAction || process.env.NEXT_RUNTIME === 'edge') {
throw new Error('Invariant: not implemented.') throw new Error('Invariant: not implemented.')
}
const redirectUrl = getURLFromRedirectError(err)
res.statusCode = 303
res.setHeader('Location', redirectUrl)
return new ActionRenderResult(JSON.stringify({}))
} else if (isNotFoundError(err)) {
if (isFetchAction) {
throw new Error('Invariant: not implemented.')
}
res.statusCode = 404
return 'not-found'
} }
const redirectUrl = getURLFromRedirectError(err)
res.statusCode = 303
res.setHeader('Location', redirectUrl)
return new ActionRenderResult(JSON.stringify({}))
} else if (isNotFoundError(err)) {
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 throw new Error('Invariant: not implemented.')
return new RenderResult(
(err as Error)?.message ?? 'Internal Server Error'
)
} }
res.statusCode = 404
return 'not-found'
}
throw err if (isFetchAction) {
res.statusCode = 500
return new RenderResult(
(err as Error)?.message ?? 'Internal Server Error'
)
} }
} else {
throw new Error('Not implemented in Edge Runtime.') throw err
} }
} }
} }
...@@ -378,8 +378,10 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -378,8 +378,10 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
return await curRenderToHTML( return await curRenderToHTML(
{ {
url: req.url, url: req.url,
method: req.method,
cookies: req.cookies, cookies: req.cookies,
headers: req.headers, headers: req.headers,
body: req.body,
} as any, } as any,
{} as any, {} as any,
pathname, pathname,
......
...@@ -131,5 +131,26 @@ createNextDescribe( ...@@ -131,5 +131,26 @@ createNextDescribe(
}) })
}) })
} }
describe('Edge SSR', () => {
it('should handle basic actions correctly', async () => {
const browser = await next.browser('/server/edge')
const cnt = await browser.elementByCss('h1').text()
expect(cnt).toBe('0')
await browser.elementByCss('#inc').click()
await check(() => browser.elementByCss('h1').text(), '1')
await browser.elementByCss('#inc').click()
await check(() => browser.elementByCss('h1').text(), '2')
await browser.elementByCss('#double').click()
await check(() => browser.elementByCss('h1').text(), '4')
await browser.elementByCss('#dec').click()
await check(() => browser.elementByCss('h1').text(), '3')
})
})
} }
) )
import Counter from '../counter'
import Form from '../form'
import dec, { inc } from '../actions'
export default function Page() {
const two = 2
return (
<>
<Counter
inc={inc}
dec={dec}
double={async (x) => {
'use server'
return x * two
}}
/>
<Form />
</>
)
}
export const runtime = 'edge'
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