Unverified Commit 5ab28cd6 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Simplify Server Action Webpack plugin (#71721)

This PR simplifies our `flight-client-entry-plugin` to not re-compute
the server reference IDs because they're already provided in `buildInfo`
via our SWC transform. It's also a small performance win depending on
the number of Server Actions in the project.

Cherry-picked from #71463.
parent ddc8807a
...@@ -149,6 +149,7 @@ export function getRSCModuleInformation( ...@@ -149,6 +149,7 @@ export function getRSCModuleInformation(
return { return {
type, type,
actions, actions,
actionIds: parsedActionsMeta,
clientRefs, clientRefs,
clientEntryType, clientEntryType,
isClientRef, isClientRef,
......
import { generateActionId } from './utils'
export type NextFlightActionEntryLoaderOptions = { export type NextFlightActionEntryLoaderOptions = {
actions: string actions: string
encryptionKey: string
} }
function nextFlightActionEntryLoader(this: any) { function nextFlightActionEntryLoader(this: any) {
const { actions, encryptionKey }: NextFlightActionEntryLoaderOptions = const { actions }: NextFlightActionEntryLoaderOptions = this.getOptions()
this.getOptions()
const actionList = JSON.parse(actions) as [string, string[]][] const actionList = JSON.parse(actions) as [
string,
[id: string, name: string][],
][]
const individualActions = actionList const individualActions = actionList
.map(([path, names]) => { .map(([path, actionsFromModule]) => {
return names.map((name) => { return actionsFromModule.map(([id, name]) => {
const id = generateActionId(encryptionKey, path, name) return [id, path, name]
return [id, path, name] as [string, string, string]
}) })
}) })
.flat() .flat()
......
import type webpack from 'webpack' import type webpack from 'webpack'
import { createHash } from 'crypto'
import { RSC_MODULE_TYPES } from '../../../shared/lib/constants' import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif', 'ico', 'svg'] const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif', 'ico', 'svg']
...@@ -47,25 +46,15 @@ export function isCSSMod(mod: { ...@@ -47,25 +46,15 @@ export function isCSSMod(mod: {
export function getActionsFromBuildInfo(mod: { export function getActionsFromBuildInfo(mod: {
resource: string resource: string
buildInfo?: any buildInfo?: any
}): undefined | string[] { }): undefined | Record<string, string> {
return mod.buildInfo?.rsc?.actions return mod.buildInfo?.rsc?.actionIds
} }
export function generateActionId( export function encodeToBase64<T extends object>(obj: T): string {
hashSalt: string,
filePath: string,
exportName: string
) {
return createHash('sha1')
.update(hashSalt + filePath + ':' + exportName)
.digest('hex')
}
export function encodeToBase64<T extends {}>(obj: T): string {
return Buffer.from(JSON.stringify(obj)).toString('base64') return Buffer.from(JSON.stringify(obj)).toString('base64')
} }
export function decodeFromBase64<T extends {}>(str: string): T { export function decodeFromBase64<T extends object>(str: string): T {
return JSON.parse(Buffer.from(str, 'base64').toString('utf8')) return JSON.parse(Buffer.from(str, 'base64').toString('utf8'))
} }
......
...@@ -25,7 +25,6 @@ import { ...@@ -25,7 +25,6 @@ import {
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { import {
getActionsFromBuildInfo, getActionsFromBuildInfo,
generateActionId,
isClientComponentEntryModule, isClientComponentEntryModule,
isCSSMod, isCSSMod,
regexCSS, regexCSS,
...@@ -43,6 +42,8 @@ import { getModuleBuildInfo } from '../loaders/get-module-build-info' ...@@ -43,6 +42,8 @@ import { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getAssumedSourceType } from '../loaders/next-flight-loader' import { getAssumedSourceType } from '../loaders/next-flight-loader'
import { isAppRouteRoute } from '../../../lib/is-app-route-route' import { isAppRouteRoute } from '../../../lib/is-app-route-route'
type ActionIdNamePair = [id: string, name: string]
interface Options { interface Options {
dev: boolean dev: boolean
appDir: string appDir: string
...@@ -283,14 +284,17 @@ export class FlightClientEntryPlugin { ...@@ -283,14 +284,17 @@ export class FlightClientEntryPlugin {
const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> = const addActionEntryList: Array<ReturnType<typeof this.injectActionEntry>> =
[] []
const actionMapsPerEntry: Record<string, Map<string, string[]>> = {} const actionMapsPerEntry: Record<
const createdActions = new Set<string>() string,
Map<string, ActionIdNamePair[]>
> = {}
const createdActionIds = new Set<string>()
// For each SC server compilation entry, we need to create its corresponding // For each SC server compilation entry, we need to create its corresponding
// client component entry. // client component entry.
forEachEntryModule(compilation, ({ name, entryModule }) => { forEachEntryModule(compilation, ({ name, entryModule }) => {
const internalClientComponentEntryImports: ClientComponentImports = {} const internalClientComponentEntryImports: ClientComponentImports = {}
const actionEntryImports = new Map<string, string[]>() const actionEntryImports = new Map<string, ActionIdNamePair[]>()
const clientEntriesToInject = [] const clientEntriesToInject = []
const mergedCSSimports: CssImports = {} const mergedCSSimports: CssImports = {}
...@@ -310,8 +314,8 @@ export class FlightClientEntryPlugin { ...@@ -310,8 +314,8 @@ export class FlightClientEntryPlugin {
resolvedModule: connection.resolvedModule, resolvedModule: connection.resolvedModule,
}) })
actionImports.forEach(([dep, names]) => actionImports.forEach(([dep, actions]) =>
actionEntryImports.set(dep, names) actionEntryImports.set(dep, actions)
) )
const isAbsoluteRequest = path.isAbsolute(entryRequest) const isAbsoluteRequest = path.isAbsolute(entryRequest)
...@@ -429,7 +433,7 @@ export class FlightClientEntryPlugin { ...@@ -429,7 +433,7 @@ export class FlightClientEntryPlugin {
actions: actionEntryImports, actions: actionEntryImports,
entryName: name, entryName: name,
bundlePath: name, bundlePath: name,
createdActions, createdActionIds,
}) })
) )
} }
...@@ -458,7 +462,10 @@ export class FlightClientEntryPlugin { ...@@ -458,7 +462,10 @@ export class FlightClientEntryPlugin {
await Promise.all(addActionEntryList) await Promise.all(addActionEntryList)
const addedClientActionEntryList: Promise<any>[] = [] const addedClientActionEntryList: Promise<any>[] = []
const actionMapsPerClientEntry: Record<string, Map<string, string[]>> = {} const actionMapsPerClientEntry: Record<
string,
Map<string, ActionIdNamePair[]>
> = {}
// We need to create extra action entries that are created from the // We need to create extra action entries that are created from the
// client layer. // client layer.
...@@ -484,7 +491,7 @@ export class FlightClientEntryPlugin { ...@@ -484,7 +491,7 @@ export class FlightClientEntryPlugin {
} }
} }
for (const [name, actionEntryImports] of Object.entries( for (const [entryName, actionEntryImports] of Object.entries(
actionMapsPerClientEntry actionMapsPerClientEntry
)) { )) {
// If an action method is already created in the server layer, we don't // If an action method is already created in the server layer, we don't
...@@ -492,13 +499,13 @@ export class FlightClientEntryPlugin { ...@@ -492,13 +499,13 @@ export class FlightClientEntryPlugin {
// This is to avoid duplicate action instances and make sure the module // This is to avoid duplicate action instances and make sure the module
// state is shared. // state is shared.
let remainingClientImportedActions = false let remainingClientImportedActions = false
const remainingActionEntryImports = new Map<string, string[]>() const remainingActionEntryImports = new Map<string, ActionIdNamePair[]>()
for (const [dep, actionNames] of actionEntryImports) { for (const [dep, actions] of actionEntryImports) {
const remainingActionNames = [] const remainingActionNames = []
for (const actionName of actionNames) { for (const action of actions) {
const id = name + '@' + dep + '@' + actionName // `action` is a [id, name] pair.
if (!createdActions.has(id)) { if (!createdActionIds.has(entryName + '@' + action[0])) {
remainingActionNames.push(actionName) remainingActionNames.push(action)
} }
} }
if (remainingActionNames.length > 0) { if (remainingActionNames.length > 0) {
...@@ -513,10 +520,10 @@ export class FlightClientEntryPlugin { ...@@ -513,10 +520,10 @@ export class FlightClientEntryPlugin {
compiler, compiler,
compilation, compilation,
actions: remainingActionEntryImports, actions: remainingActionEntryImports,
entryName: name, entryName,
bundlePath: name, bundlePath: entryName,
fromClient: true, fromClient: true,
createdActions, createdActionIds,
}) })
) )
} }
...@@ -533,7 +540,7 @@ export class FlightClientEntryPlugin { ...@@ -533,7 +540,7 @@ export class FlightClientEntryPlugin {
dependencies: ReturnType<typeof webpack.EntryPlugin.createDependency>[] dependencies: ReturnType<typeof webpack.EntryPlugin.createDependency>[]
}) { }) {
// action file path -> action names // action file path -> action names
const collectedActions = new Map<string, string[]>() const collectedActions = new Map<string, ActionIdNamePair[]>()
// Keep track of checked modules to avoid infinite loops with recursive imports. // Keep track of checked modules to avoid infinite loops with recursive imports.
const visitedModule = new Set<string>() const visitedModule = new Set<string>()
...@@ -558,7 +565,7 @@ export class FlightClientEntryPlugin { ...@@ -558,7 +565,7 @@ export class FlightClientEntryPlugin {
const actions = getActionsFromBuildInfo(mod) const actions = getActionsFromBuildInfo(mod)
if (actions) { if (actions) {
collectedActions.set(modResource, actions) collectedActions.set(modResource, Object.entries(actions))
} }
// Collect used exported actions transversely. // Collect used exported actions transversely.
...@@ -617,14 +624,14 @@ export class FlightClientEntryPlugin { ...@@ -617,14 +624,14 @@ export class FlightClientEntryPlugin {
}): { }): {
cssImports: CssImports cssImports: CssImports
clientComponentImports: ClientComponentImports clientComponentImports: ClientComponentImports
actionImports: [string, string[]][] actionImports: [string, ActionIdNamePair[]][]
} { } {
// Keep track of checked modules to avoid infinite loops with recursive imports. // Keep track of checked modules to avoid infinite loops with recursive imports.
const visitedOfClientComponentsTraverse = new Set() const visitedOfClientComponentsTraverse = new Set()
// Info to collect. // Info to collect.
const clientComponentImports: ClientComponentImports = {} const clientComponentImports: ClientComponentImports = {}
const actionImports: [string, string[]][] = [] const actionImports: [string, ActionIdNamePair[]][] = []
const CSSImports = new Set<string>() const CSSImports = new Set<string>()
const filterClientComponents = ( const filterClientComponents = (
...@@ -652,7 +659,7 @@ export class FlightClientEntryPlugin { ...@@ -652,7 +659,7 @@ export class FlightClientEntryPlugin {
const actions = getActionsFromBuildInfo(mod) const actions = getActionsFromBuildInfo(mod)
if (actions) { if (actions) {
actionImports.push([modResource, actions]) actionImports.push([modResource, Object.entries(actions)])
} }
if (isCSSMod(mod)) { if (isCSSMod(mod)) {
...@@ -839,20 +846,20 @@ export class FlightClientEntryPlugin { ...@@ -839,20 +846,20 @@ export class FlightClientEntryPlugin {
entryName, entryName,
bundlePath, bundlePath,
fromClient, fromClient,
createdActions, createdActionIds,
}: { }: {
compiler: webpack.Compiler compiler: webpack.Compiler
compilation: webpack.Compilation compilation: webpack.Compilation
actions: Map<string, string[]> actions: Map<string, ActionIdNamePair[]>
entryName: string entryName: string
bundlePath: string bundlePath: string
createdActions: Set<string> createdActionIds: Set<string>
fromClient?: boolean fromClient?: boolean
}) { }) {
const actionsArray = Array.from(actions.entries()) const actionsArray = Array.from(actions.entries())
for (const [dep, actionNames] of actions) { for (const [, actionsFromModule] of actions) {
for (const actionName of actionNames) { for (const [id] of actionsFromModule) {
createdActions.add(entryName + '@' + dep + '@' + actionName) createdActionIds.add(entryName + '@' + id)
} }
} }
...@@ -862,7 +869,6 @@ export class FlightClientEntryPlugin { ...@@ -862,7 +869,6 @@ export class FlightClientEntryPlugin {
const actionLoader = `next-flight-action-entry-loader?${stringify({ const actionLoader = `next-flight-action-entry-loader?${stringify({
actions: JSON.stringify(actionsArray), actions: JSON.stringify(actionsArray),
encryptionKey: this.encryptionKey,
__client_imported__: fromClient, __client_imported__: fromClient,
})}!` })}!`
...@@ -870,9 +876,8 @@ export class FlightClientEntryPlugin { ...@@ -870,9 +876,8 @@ export class FlightClientEntryPlugin {
? pluginState.edgeServerActions ? pluginState.edgeServerActions
: pluginState.serverActions : pluginState.serverActions
for (const [actionFilePath, actionNames] of actionsArray) { for (const [, actionsFromModule] of actionsArray) {
for (const name of actionNames) { for (const [id] of actionsFromModule) {
const id = generateActionId(this.encryptionKey, actionFilePath, name)
if (typeof currentCompilerServerActions[id] === 'undefined') { if (typeof currentCompilerServerActions[id] === 'undefined') {
currentCompilerServerActions[id] = { currentCompilerServerActions[id] = {
workers: {}, workers: {},
......
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