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(
: null
const entriesWithAction = actionManifest ? new Set() : null
if (actionManifest && entriesWithAction) {
for (const id in actionManifest) {
for (const entry in actionManifest[id].workers) {
for (const id in actionManifest.node) {
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)
}
}
......
......@@ -44,18 +44,21 @@ interface Options {
const PLUGIN_NAME = 'ClientEntryPlugin'
export type ActionManifest = {
[actionId: string]: {
workers: {
[name: string]: string | number
[key in 'node' | 'edge']: {
[actionId: string]: {
workers: {
[name: string]: string | number
}
}
}
}
const pluginState = getProxiedPluginState({
// A map to track "action" -> "list of bundles".
serverActions: {} as ActionManifest,
edgeServerActions: {} as ActionManifest,
actionModId: {} as Record<string, string | number>,
serverActions: {} as ActionManifest['node'],
edgeServerActions: {} as ActionManifest['edge'],
actionModServerId: {} as Record<string, string | number>,
actionModEdgeServerId: {} as Record<string, string | number>,
// Manifest of CSS entry files for server/edge server.
serverCSSManifest: {} as ClientCSSReferenceManifest,
......@@ -78,12 +81,14 @@ export class ClientReferenceEntryPlugin {
appDir: string
isEdgeServer: boolean
useExperimentalReact: boolean
assetPrefix: string
constructor(options: Options) {
this.dev = options.dev
this.appDir = options.appDir
this.isEdgeServer = options.isEdgeServer
this.useExperimentalReact = options.useExperimentalReact
this.assetPrefix = !this.dev && !this.isEdgeServer ? '../' : ''
}
apply(compiler: webpack.Compiler) {
......@@ -152,8 +157,6 @@ export class ClientReferenceEntryPlugin {
compilation.hooks.processAssets.tap(
{
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,
},
(assets) => this.createAsset(compilation, assets)
......@@ -237,13 +240,6 @@ export class ClientReferenceEntryPlugin {
})
)
// Create action entry
if (this.isEdgeServer) {
pluginState.edgeServerActions = {}
} else {
pluginState.serverActions = {}
}
if (actionEntryImports.size > 0) {
if (!this.useExperimentalReact) {
warnOnce(
......@@ -424,8 +420,6 @@ export class ClientReferenceEntryPlugin {
compilation.hooks.processAssets.tap(
{
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,
},
(assets: webpack.Compilation['assets']) => {
......@@ -440,12 +434,14 @@ export class ClientReferenceEntryPlugin {
},
}
const manifest = JSON.stringify(data, null, this.dev ? 2 : undefined)
assets[FLIGHT_SERVER_CSS_MANIFEST + '.json'] = new sources.RawSource(
manifest
) as unknown as webpack.sources.RawSource
assets[FLIGHT_SERVER_CSS_MANIFEST + '.js'] = new sources.RawSource(
'self.__RSC_CSS_MANIFEST=' + manifest
) as unknown as webpack.sources.RawSource
assets[`${this.assetPrefix}${FLIGHT_SERVER_CSS_MANIFEST}.json`] =
new sources.RawSource(
manifest
) as unknown as webpack.sources.RawSource
assets[`${this.assetPrefix}${FLIGHT_SERVER_CSS_MANIFEST}.js`] =
new sources.RawSource(
'self.__RSC_CSS_MANIFEST=' + manifest
) as unknown as webpack.sources.RawSource
}
)
......@@ -723,9 +719,9 @@ export class ClientReferenceEntryPlugin {
actions: JSON.stringify(actionsArray),
})}!`
let currentCompilerServerActions = this.isEdgeServer
? pluginState.serverActions
: pluginState.edgeServerActions
const currentCompilerServerActions = this.isEdgeServer
? pluginState.edgeServerActions
: pluginState.serverActions
for (const [p, names] of actionsArray) {
for (const name of names) {
const id = generateActionId(p, name)
......@@ -795,31 +791,46 @@ export class ClientReferenceEntryPlugin {
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 = {
...pluginState.serverActions,
...pluginState.edgeServerActions,
const serverActions: ActionManifest['node'] = {}
for (let id in pluginState.serverActions) {
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) {
action.workers[name] = pluginState.actionModId[name]
action.workers[name] = pluginState.actionModEdgeServerId[name]
}
edgeServerActions[id] = action
}
const json = JSON.stringify(
fullServerActions,
{
node: serverActions,
edge: edgeServerActions,
},
null,
this.dev ? 2 : undefined
)
assets[SERVER_REFERENCE_MANIFEST + '.js'] = new sources.RawSource(
'self.__RSC_SERVER_MANIFEST=' + json
) as unknown as webpack.sources.RawSource
assets[SERVER_REFERENCE_MANIFEST + '.json'] = new sources.RawSource(
json
) as unknown as webpack.sources.RawSource
assets[`${this.assetPrefix}${SERVER_REFERENCE_MANIFEST}.js`] =
new sources.RawSource(
'self.__RSC_SERVER_MANIFEST=' + json
) 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({
req.method === 'POST'
if (isFetchAction || isFormAction || isMultipartAction) {
if (process.env.NEXT_RUNTIME !== 'edge') {
try {
let bound = []
let bound = []
const workerName = 'app' + pathname
const { decodeReply } = ComponentMod
const workerName = 'app' + pathname
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) {
const formFields: any[] = []
......@@ -68,7 +102,7 @@ export async function handleAction({
{
get: (_, id: string) => {
return {
id: serverActionsManifest[id].workers[workerName],
id: serverActionsManifest.node[id].workers[workerName],
name: id,
chunks: [],
}
......@@ -93,45 +127,46 @@ export async function handleAction({
bound = await decodeReply(actionData)
}
}
}
const actionModId = serverActionsManifest[actionId].workers[workerName]
const actionHandler =
ComponentMod.__next_app_webpack_require__(actionModId)[actionId]
const actionModId =
serverActionsManifest[
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 result = new ActionRenderResult(JSON.stringify([returnVal]))
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
return result
}
} catch (err) {
if (isRedirectError(err)) {
if (isFetchAction) {
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 returnVal = await actionHandler.apply(null, bound)
const result = new ActionRenderResult(JSON.stringify([returnVal]))
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
return result
}
} catch (err) {
if (isRedirectError(err)) {
if (isFetchAction || process.env.NEXT_RUNTIME === 'edge') {
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) {
res.statusCode = 500
return new RenderResult(
(err as Error)?.message ?? 'Internal Server Error'
)
throw new Error('Invariant: not implemented.')
}
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> {
return await curRenderToHTML(
{
url: req.url,
method: req.method,
cookies: req.cookies,
headers: req.headers,
body: req.body,
} as any,
{} as any,
pathname,
......
......@@ -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