Unverified Commit 9c9f4264 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Remove unused Server IDs tracking on the server graph (#70317)

Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent bd19545a
...@@ -5,15 +5,6 @@ import { RSC_MODULE_TYPES } from '../../../shared/lib/constants' ...@@ -5,15 +5,6 @@ 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']
const imageRegex = new RegExp(`\\.(${imageExtensions.join('|')})$`) const imageRegex = new RegExp(`\\.(${imageExtensions.join('|')})$`)
// Determine if the whole module is server action, 'use server' in the top level of module
export function isActionServerLayerEntryModule(mod: {
resource: string
buildInfo?: any
}) {
const rscInfo = mod.buildInfo.rsc
return !!(rscInfo?.actions && rscInfo?.type === RSC_MODULE_TYPES.server)
}
// Determine if the whole module is client action, 'use server' in nested closure in the client module // Determine if the whole module is client action, 'use server' in nested closure in the client module
function isActionClientLayerModule(mod: { resource: string; buildInfo?: any }) { function isActionClientLayerModule(mod: { resource: string; buildInfo?: any }) {
const rscInfo = mod.buildInfo.rsc const rscInfo = mod.buildInfo.rsc
......
...@@ -29,7 +29,6 @@ import { ...@@ -29,7 +29,6 @@ import {
isClientComponentEntryModule, isClientComponentEntryModule,
isCSSMod, isCSSMod,
regexCSS, regexCSS,
isActionServerLayerEntryModule,
} from '../loaders/utils' } from '../loaders/utils'
import { import {
traverseModules, traverseModules,
...@@ -76,11 +75,6 @@ const pluginState = getProxiedPluginState({ ...@@ -76,11 +75,6 @@ const pluginState = getProxiedPluginState({
serverActions: {} as ActionManifest['node'], serverActions: {} as ActionManifest['node'],
edgeServerActions: {} as ActionManifest['edge'], edgeServerActions: {} as ActionManifest['edge'],
usedActions: {
node: {} as Record<string, Set<string>>,
edge: {} as Record<string, Set<string>>,
},
actionModServerId: {} as Record< actionModServerId: {} as Record<
string, string,
{ {
...@@ -163,15 +157,6 @@ function deduplicateCSSImportsForEntry(mergedCSSimports: CssImports) { ...@@ -163,15 +157,6 @@ function deduplicateCSSImportsForEntry(mergedCSSimports: CssImports) {
return dedupedCSSImports return dedupedCSSImports
} }
// Collection of action module path and action names per runtime.
type UsedActionMap = {
node: Record<string, Set<string>>
edge: Record<string, Set<string>>
}
type UsedActionPerEntry = {
[entryName: string]: UsedActionMap
}
export class FlightClientEntryPlugin { export class FlightClientEntryPlugin {
dev: boolean dev: boolean
appDir: string appDir: string
...@@ -180,9 +165,6 @@ export class FlightClientEntryPlugin { ...@@ -180,9 +165,6 @@ export class FlightClientEntryPlugin {
assetPrefix: string assetPrefix: string
webpackRuntime: string webpackRuntime: string
// Collect the used actions based on the entry name and runtime.
usedActions: UsedActionPerEntry
constructor(options: Options) { constructor(options: Options) {
this.dev = options.dev this.dev = options.dev
this.appDir = options.appDir this.appDir = options.appDir
...@@ -192,40 +174,6 @@ export class FlightClientEntryPlugin { ...@@ -192,40 +174,6 @@ export class FlightClientEntryPlugin {
this.webpackRuntime = this.isEdgeServer this.webpackRuntime = this.isEdgeServer
? EDGE_RUNTIME_WEBPACK ? EDGE_RUNTIME_WEBPACK
: DEFAULT_RUNTIME_WEBPACK : DEFAULT_RUNTIME_WEBPACK
this.usedActions = {}
}
getUsedActionsInEntry(
entryName: string,
modResource: string
): Set<string> | undefined {
const runtime = this.isEdgeServer ? 'edge' : 'node'
const actionsRuntimeMap = this.usedActions[entryName]
const actionMap = actionsRuntimeMap ? actionsRuntimeMap[runtime] : undefined
return actionMap ? actionMap[modResource] : undefined
}
setUsedActionsInEntry(
entryName: string,
modResource: string,
actionNames: string[]
) {
const runtime = this.isEdgeServer ? 'edge' : 'node'
if (!this.usedActions[entryName]) {
this.usedActions[entryName] = {
node: {},
edge: {},
}
}
if (!this.usedActions[entryName][runtime]) {
this.usedActions[entryName][runtime] = {}
}
const actionsMap = this.usedActions[entryName][runtime]
if (!actionsMap[modResource]) {
actionsMap[modResource] = new Set()
}
actionNames.forEach((name) => actionsMap[modResource].add(name))
} }
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
...@@ -339,7 +287,6 @@ export class FlightClientEntryPlugin { ...@@ -339,7 +287,6 @@ export class FlightClientEntryPlugin {
const { clientComponentImports, actionImports, cssImports } = const { clientComponentImports, actionImports, cssImports } =
this.collectComponentInfoFromServerEntryDependency({ this.collectComponentInfoFromServerEntryDependency({
entryName: name,
entryRequest, entryRequest,
compilation, compilation,
resolvedModule: connection.resolvedModule, resolvedModule: connection.resolvedModule,
...@@ -502,7 +449,6 @@ export class FlightClientEntryPlugin { ...@@ -502,7 +449,6 @@ export class FlightClientEntryPlugin {
// Collect from all entries, e.g. layout.js, page.js, loading.js, ... // Collect from all entries, e.g. layout.js, page.js, loading.js, ...
// add aggregate them. // add aggregate them.
const actionEntryImports = this.collectClientActionsFromDependencies({ const actionEntryImports = this.collectClientActionsFromDependencies({
entryName: name,
compilation, compilation,
dependencies: ssrEntryDependencies, dependencies: ssrEntryDependencies,
}) })
...@@ -560,11 +506,9 @@ export class FlightClientEntryPlugin { ...@@ -560,11 +506,9 @@ export class FlightClientEntryPlugin {
} }
collectClientActionsFromDependencies({ collectClientActionsFromDependencies({
entryName,
compilation, compilation,
dependencies, dependencies,
}: { }: {
entryName: string
compilation: webpack.Compilation compilation: webpack.Compilation
dependencies: ReturnType<typeof webpack.EntryPlugin.createDependency>[] dependencies: ReturnType<typeof webpack.EntryPlugin.createDependency>[]
}) { }) {
...@@ -582,27 +526,17 @@ export class FlightClientEntryPlugin { ...@@ -582,27 +526,17 @@ export class FlightClientEntryPlugin {
entryRequest: string entryRequest: string
resolvedModule: any resolvedModule: any
}) => { }) => {
const collectActionsInDep = ( const collectActionsInDep = (mod: webpack.NormalModule): void => {
mod: webpack.NormalModule,
ids: string[]
): void => {
if (!mod) return if (!mod) return
const modResource = getModuleResource(mod) const modResource = getModuleResource(mod)
if (!modResource) return if (!modResource) return
const actions = getActionsFromBuildInfo(mod)
// Collect used exported actions.
if (visitedModule.has(modResource) && actions) {
this.setUsedActionsInEntry(entryName, modResource, ids)
}
if (visitedModule.has(modResource)) return if (visitedModule.has(modResource)) return
visitedModule.add(modResource) visitedModule.add(modResource)
const actions = getActionsFromBuildInfo(mod)
if (actions) { if (actions) {
collectedActions.set(modResource, actions) collectedActions.set(modResource, actions)
} }
...@@ -610,17 +544,8 @@ export class FlightClientEntryPlugin { ...@@ -610,17 +544,8 @@ export class FlightClientEntryPlugin {
// Collect used exported actions transversely. // Collect used exported actions transversely.
getModuleReferencesInOrder(mod, compilation.moduleGraph).forEach( getModuleReferencesInOrder(mod, compilation.moduleGraph).forEach(
(connection: any) => { (connection: any) => {
let dependencyIds: string[] = []
const depModule = connection.dependency
if (depModule?.ids) {
dependencyIds.push(...depModule.ids)
} else {
dependencyIds = depModule.category === 'esm' ? [] : ['*']
}
collectActionsInDep( collectActionsInDep(
connection.resolvedModule as webpack.NormalModule, connection.resolvedModule as webpack.NormalModule
dependencyIds
) )
} }
) )
...@@ -632,7 +557,7 @@ export class FlightClientEntryPlugin { ...@@ -632,7 +557,7 @@ export class FlightClientEntryPlugin {
!entryRequest.includes('next-flight-action-entry-loader') !entryRequest.includes('next-flight-action-entry-loader')
) { ) {
// Traverse the module graph to find all client components. // Traverse the module graph to find all client components.
collectActionsInDep(resolvedModule, []) collectActionsInDep(resolvedModule)
} }
} }
...@@ -662,12 +587,10 @@ export class FlightClientEntryPlugin { ...@@ -662,12 +587,10 @@ export class FlightClientEntryPlugin {
} }
collectComponentInfoFromServerEntryDependency({ collectComponentInfoFromServerEntryDependency({
entryName,
entryRequest, entryRequest,
compilation, compilation,
resolvedModule, resolvedModule,
}: { }: {
entryName: string
entryRequest: string entryRequest: string
compilation: webpack.Compilation compilation: webpack.Compilation
resolvedModule: any /* Dependency */ resolvedModule: any /* Dependency */
...@@ -678,7 +601,6 @@ export class FlightClientEntryPlugin { ...@@ -678,7 +601,6 @@ export class FlightClientEntryPlugin {
} { } {
// 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()
const visitedOfActionTraverse = new Set()
// Info to collect. // Info to collect.
const clientComponentImports: ClientComponentImports = {} const clientComponentImports: ClientComponentImports = {}
...@@ -758,56 +680,9 @@ export class FlightClientEntryPlugin { ...@@ -758,56 +680,9 @@ export class FlightClientEntryPlugin {
) )
} }
const filterUsedActions = (
mod: webpack.NormalModule,
importedIdentifiers: string[]
): void => {
if (!mod) return
const modResource = getModuleResource(mod)
if (!modResource) return
if (visitedOfActionTraverse.has(modResource)) {
if (this.getUsedActionsInEntry(entryName, modResource)) {
this.setUsedActionsInEntry(
entryName,
modResource,
importedIdentifiers
)
}
return
}
visitedOfActionTraverse.add(modResource)
if (isActionServerLayerEntryModule(mod)) {
// `ids` are the identifiers that are imported from the dependency,
// if it's present, it's an array of strings.
this.setUsedActionsInEntry(entryName, modResource, importedIdentifiers)
return
}
getModuleReferencesInOrder(mod, compilation.moduleGraph).forEach(
(connection: any) => {
let dependencyIds: string[] = []
const depModule = connection.dependency
if (depModule?.ids) {
dependencyIds.push(...depModule.ids)
} else {
dependencyIds = depModule.category === 'esm' ? [] : ['*']
}
filterUsedActions(connection.resolvedModule, dependencyIds)
}
)
}
// Traverse the module graph to find all client components. // Traverse the module graph to find all client components.
filterClientComponents(resolvedModule, []) filterClientComponents(resolvedModule, [])
// Traverse the module graph to find all used actions.
filterUsedActions(resolvedModule, [])
return { return {
clientComponentImports, clientComponentImports,
cssImports: CSSImports.size cssImports: CSSImports.size
...@@ -954,29 +829,7 @@ export class FlightClientEntryPlugin { ...@@ -954,29 +829,7 @@ export class FlightClientEntryPlugin {
createdActions: Set<string> createdActions: Set<string>
fromClient?: boolean fromClient?: boolean
}) { }) {
// Filter out the unused actions before create action entry.
for (const [filePath, names] of actions.entries()) {
const usedActionNames = this.getUsedActionsInEntry(entryName, filePath)
if (!usedActionNames) continue
const containsAll = usedActionNames.has('*')
if (usedActionNames && !containsAll) {
const filteredNames = names.filter(
(name) => usedActionNames.has(name) || isInlineActionIdentifier(name)
)
actions.set(filePath, filteredNames)
} else if (!containsAll) {
// If we didn't collect the used, we erase them from the collected actions
// to avoid creating the action entry.
if (
names.filter((name) => !isInlineActionIdentifier(name)).length === 0
) {
actions.delete(filePath)
}
}
}
const actionsArray = Array.from(actions.entries()) const actionsArray = Array.from(actions.entries())
for (const [dep, actionNames] of actions) { for (const [dep, actionNames] of actions) {
for (const actionName of actionNames) { for (const actionName of actionNames) {
createdActions.add(entryName + '@' + dep + '@' + actionName) createdActions.add(entryName + '@' + dep + '@' + actionName)
...@@ -1210,8 +1063,3 @@ function getModuleResource(mod: webpack.NormalModule): string { ...@@ -1210,8 +1063,3 @@ function getModuleResource(mod: webpack.NormalModule): string {
} }
return modResource return modResource
} }
// x-ref crates/next-custom-transforms/src/transforms/server_actions.rs `gen_ident` funcition
function isInlineActionIdentifier(name: string) {
return name.startsWith('$$RSC_SERVER_')
}
...@@ -4,7 +4,8 @@ import { ...@@ -4,7 +4,8 @@ import {
markLayoutAsEdge, markLayoutAsEdge,
} from '../_testing/utils' } from '../_testing/utils'
describe('actions-tree-shaking - basic', () => { // TODO: revisit when we have a better side-effect free transform approach for server action
describe.skip('actions-tree-shaking - basic', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
...@@ -4,7 +4,8 @@ import { ...@@ -4,7 +4,8 @@ import {
markLayoutAsEdge, markLayoutAsEdge,
} from '../_testing/utils' } from '../_testing/utils'
describe('actions-tree-shaking - mixed-module-actions', () => { // TODO: revisit when we have a better side-effect free transform approach for server action
describe.skip('actions-tree-shaking - mixed-module-actions', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
'use server'
export async function action() {
console.log('action: test-1')
}
'use client'
import { action } from '../actions'
import { getFoo } from '../nested'
export default function Page() {
return (
<>
<form action={action}>
<button type="submit" id="test-1">
Test 1 Submit
</button>
</form>
<button
onClick={async () => {
const foo = await getFoo()
await foo()
}}
id="test-2"
>
Test 2 Submit
</button>
</>
)
}
'use server'
export async function foo() {
console.log('action: test-2')
}
export async function getFoo() {
return foo
}
import { action } from '../actions'
import { getFoo } from '../nested'
export default async function Page() {
const foo = await getFoo()
await action()
await foo()
return <>server</>
}
export const dynamic = 'force-dynamic'
...@@ -3,36 +3,66 @@ import { ...@@ -3,36 +3,66 @@ import {
getActionsRoutesStateByRuntime, getActionsRoutesStateByRuntime,
markLayoutAsEdge, markLayoutAsEdge,
} from '../_testing/utils' } from '../_testing/utils'
import { retry } from 'next-test-utils'
describe('actions-tree-shaking - reexport', () => { // TODO: revisit when we have a better side-effect free transform approach for server action
describe.skip('actions-tree-shaking - reexport', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (process.env.TEST_EDGE) { if (process.env.TEST_EDGE) {
markLayoutAsEdge(next) markLayoutAsEdge(next)
} }
it('should not have the unused action in the manifest', async () => { it('should not tree-shake namespace exports the manifest', async () => {
const actionsRoutesState = await getActionsRoutesStateByRuntime(next) const actionsRoutesState = await getActionsRoutesStateByRuntime(next)
expect(actionsRoutesState).toMatchObject({ expect(actionsRoutesState).toMatchObject({
'app/namespace-reexport/server/page': { 'app/namespace-reexport/server/page': {
// Turbopack does not tree-shake server side chunks rsc: 3,
rsc: process.env.TURBOPACK ? 3 : 1,
}, },
'app/namespace-reexport/client/page': { 'app/namespace-reexport/client/page': {
// Turbopack does not support tree-shaking export * as we don't have global information 'action-browser': 3,
'action-browser': process.env.TURBOPACK ? 3 : 1,
}, },
// We're not able to tree-shake these re-exports here in webpack mode
'app/named-reexport/server/page': { 'app/named-reexport/server/page': {
// Turbopack supports tree-shaking these re-exports rsc: 3,
rsc: process.env.TURBOPACK ? 1 : 3,
}, },
'app/named-reexport/client/page': { 'app/namespace-reexport-2/client/page': {
'action-browser': 3, 'action-browser': 3,
}, },
'app/namespace-reexport-2/server/page': {
rsc: 3,
},
})
})
it('should keep all the action exports for namespace export case on client layer', async () => {
const browser = await next.browser('/namespace-reexport-2/client')
const outputSize = next.cliOutput.length
await browser.elementByCss('#test-1').click()
await retry(async () => {
const output = next.cliOutput.slice(outputSize)
expect(output).toContain('action: test-1')
})
await browser.elementByCss('#test-2').click()
await retry(async () => {
const output = next.cliOutput.slice(outputSize)
expect(output).toContain('action: test-2')
})
})
it('should keep all the action exports for namespace export case on server layer', async () => {
const outputSize = next.cliOutput.length
await next.browser('/namespace-reexport-2/server')
await retry(async () => {
const output = next.cliOutput.slice(outputSize)
expect(output).toContain('action: test-1')
expect(output).toContain('action: test-2')
}) })
}) })
}) })
...@@ -4,7 +4,8 @@ import { ...@@ -4,7 +4,8 @@ import {
markLayoutAsEdge, markLayoutAsEdge,
} from '../_testing/utils' } from '../_testing/utils'
describe('actions-tree-shaking - shared-module-actions', () => { // TODO: revisit when we have a better side-effect free transform approach for server action
describe.skip('actions-tree-shaking - shared-module-actions', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
...@@ -4,7 +4,8 @@ import { ...@@ -4,7 +4,8 @@ import {
markLayoutAsEdge, markLayoutAsEdge,
} from '../_testing/utils' } from '../_testing/utils'
describe('actions-tree-shaking - use-effect-actions', () => { // TODO: revisit when we have a better side-effect free transform approach for server action
describe.skip('actions-tree-shaking - use-effect-actions', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
...@@ -15597,96 +15597,6 @@ ...@@ -15597,96 +15597,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/production/app-dir/actions-tree-shaking/basic/basic-edge.test.ts": {
"passed": [],
"failed": [
"actions-tree-shaking - basic should not have the unused action in the manifest"
],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/basic/basic.test.ts": {
"passed": [
"actions-tree-shaking - basic should not have the unused action in the manifest"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/mixed-module-actions/mixed-module-actions-edge.test.ts": {
"passed": [
"actions-tree-shaking - mixed-module-actions should not do tree shake for cjs module when import server actions"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/mixed-module-actions/mixed-module-actions.test.ts": {
"passed": [
"actions-tree-shaking - mixed-module-actions should not do tree shake for cjs module when import server actions"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/reexport/reexport-edge.test.ts": {
"passed": [
"actions-tree-shaking - reexport should not have the unused action in the manifest"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/reexport/reexport.test.ts": {
"passed": [
"actions-tree-shaking - reexport should not have the unused action in the manifest"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/shared-module-actions/shared-module-actions-edge.test.ts": {
"passed": [
"actions-tree-shaking - shared-module-actions should not have the unused action in the manifest"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/shared-module-actions/shared-module-actions.test.ts": {
"passed": [
"actions-tree-shaking - shared-module-actions should not have the unused action in the manifest"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/use-effect-actions/use-effect-actions-edge.test.ts": {
"passed": [],
"failed": [
"actions-tree-shaking - use-effect-actions should not tree shake the used action under useEffect"
],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/use-effect-actions/use-effect-actions.test.ts": {
"passed": [],
"failed": [
"actions-tree-shaking - use-effect-actions should not tree shake the used action under useEffect"
],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/production/app-dir/actions-tree-shaking/client-actions-tree-shaking/client-actions-tree-shaking.test.ts": { "test/production/app-dir/actions-tree-shaking/client-actions-tree-shaking/client-actions-tree-shaking.test.ts": {
"passed": [], "passed": [],
"failed": [ "failed": [
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