Unverified Commit ac7f2b6f authored by LongYinan's avatar LongYinan Committed by GitHub

Make turbotrace run after the webpack build (#45621)

- [x] Depends on https://github.com/vercel/next.js/pull/45776

Turbotrace occupies too many memories while running; this PR makes it
run after the webpack build is finished, it can reduce the memory
hogging by webpack and turbotrace, thus avoiding OOM

The `maxFiles` option in turbotrace is removed because there is
`memoryLimit` option takes over its role.

Close WEB-556
parent e13ace58
...@@ -7,7 +7,7 @@ on: ...@@ -7,7 +7,7 @@ on:
name: Build, test, and deploy name: Build, test, and deploy
env: env:
NAPI_CLI_VERSION: 2.13.3 NAPI_CLI_VERSION: 2.14.7
TURBO_VERSION: 1.6.3 TURBO_VERSION: 1.6.3
RUST_TOOLCHAIN: nightly-2022-11-04 RUST_TOOLCHAIN: nightly-2022-11-04
PNPM_VERSION: 7.24.3 PNPM_VERSION: 7.24.3
...@@ -932,8 +932,10 @@ jobs: ...@@ -932,8 +932,10 @@ jobs:
with: with:
image: ghcr.io/napi-rs/napi-rs/nodejs-rust:stable-2022-10-24-x64 image: ghcr.io/napi-rs/napi-rs/nodejs-rust:stable-2022-10-24-x64
options: -e RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }} -e NAPI_CLI_VERSION=${{ env.NAPI_CLI_VERSION }} -e TURBO_VERSION=${{ env.TURBO_VERSION }} -v ${{ env.HOME }}/.cargo/git:/root/.cargo/git -v ${{ env.HOME }}/.cargo/registry:/root/.cargo/registry -v ${{ github.workspace }}:/build -w /build options: -e RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }} -e NAPI_CLI_VERSION=${{ env.NAPI_CLI_VERSION }} -e TURBO_VERSION=${{ env.TURBO_VERSION }} -v ${{ env.HOME }}/.cargo/git:/root/.cargo/git -v ${{ env.HOME }}/.cargo/registry:/root/.cargo/registry -v ${{ github.workspace }}:/build -w /build
# turn on some optimization while building Rust codes to prevent tests timeout
run: | run: |
set -e && set -e &&
export CARGO_PROFILE_DEV_OPT_LEVEL=1 &&
rustup toolchain install "${RUST_TOOLCHAIN}" && rustup toolchain install "${RUST_TOOLCHAIN}" &&
rustup default "${RUST_TOOLCHAIN}" && rustup default "${RUST_TOOLCHAIN}" &&
rustup target add x86_64-unknown-linux-gnu && rustup target add x86_64-unknown-linux-gnu &&
......
...@@ -5,7 +5,7 @@ on: ...@@ -5,7 +5,7 @@ on:
name: Generate Pull Request Stats name: Generate Pull Request Stats
env: env:
NAPI_CLI_VERSION: 2.13.3 NAPI_CLI_VERSION: 2.14.7
TURBO_VERSION: 1.6.3 TURBO_VERSION: 1.6.3
RUST_TOOLCHAIN: nightly-2022-11-04 RUST_TOOLCHAIN: nightly-2022-11-04
PNPM_VERSION: 7.24.3 PNPM_VERSION: 7.24.3
......
...@@ -101,15 +101,8 @@ module.exports = { ...@@ -101,15 +101,8 @@ module.exports = {
// if there is `process.cwd()` expression in your code, you can set this option to tell `turbotrace` the value of `process.cwd()` while tracing. // if there is `process.cwd()` expression in your code, you can set this option to tell `turbotrace` the value of `process.cwd()` while tracing.
// for example the require(process.cwd() + '/package.json') will be traced as require('/path/to/cwd/package.json') // for example the require(process.cwd() + '/package.json') will be traced as require('/path/to/cwd/package.json')
processCwd?: string processCwd?: string
// control the maximum number of files that are passed to the `turbotrace` // control the maximum memory usage of the `turbotrace`, in `MB`, default is `6000`.
// default is 128
maxFiles?: number
// control the maximum memory usage of the `turbotrace`, in `MB`
memoryLimit?: number memoryLimit?: number
// control if the webpack entries should be skipped when tracing
// tracing the entries is not necessary for applications that all assets could be traced in the dist files
// default is `false`
skipEntries?: boolean
}, },
}, },
} }
......
...@@ -31,6 +31,6 @@ ...@@ -31,6 +31,6 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@napi-rs/cli": "2.13.3" "@napi-rs/cli": "2.14.7"
} }
} }
...@@ -125,7 +125,7 @@ ...@@ -125,7 +125,7 @@
"@babel/types": "7.18.0", "@babel/types": "7.18.0",
"@edge-runtime/primitives": "2.0.0", "@edge-runtime/primitives": "2.0.0",
"@hapi/accept": "5.0.2", "@hapi/accept": "5.0.2",
"@napi-rs/cli": "2.13.3", "@napi-rs/cli": "2.14.7",
"@napi-rs/triples": "1.1.0", "@napi-rs/triples": "1.1.0",
"@next/polyfill-module": "13.1.7-canary.8", "@next/polyfill-module": "13.1.7-canary.8",
"@next/polyfill-nomodule": "13.1.7-canary.8", "@next/polyfill-nomodule": "13.1.7-canary.8",
......
This diff is collapsed.
...@@ -20,6 +20,10 @@ import { createEntrypoints } from './entries' ...@@ -20,6 +20,10 @@ import { createEntrypoints } from './entries'
import loadConfig from '../server/config' import loadConfig from '../server/config'
import { trace } from '../trace' import { trace } from '../trace'
import { WEBPACK_LAYERS } from '../lib/constants' import { WEBPACK_LAYERS } from '../lib/constants'
import {
TraceEntryPointsPlugin,
TurbotraceContext,
} from './webpack/plugins/next-trace-entrypoints-plugin'
type CompilerResult = { type CompilerResult = {
errors: webpack.StatsError[] errors: webpack.StatsError[]
...@@ -37,7 +41,16 @@ function isTelemetryPlugin(plugin: unknown): plugin is TelemetryPlugin { ...@@ -37,7 +41,16 @@ function isTelemetryPlugin(plugin: unknown): plugin is TelemetryPlugin {
return plugin instanceof TelemetryPlugin return plugin instanceof TelemetryPlugin
} }
async function webpackBuildImpl(): Promise<number> { function isTraceEntryPointsPlugin(
plugin: unknown
): plugin is TraceEntryPointsPlugin {
return plugin instanceof TraceEntryPointsPlugin
}
async function webpackBuildImpl(): Promise<{
duration: number
turbotraceContext?: TurbotraceContext
}> {
let result: CompilerResult | null = { let result: CompilerResult | null = {
warnings: [], warnings: [],
errors: [], errors: [],
...@@ -117,6 +130,7 @@ async function webpackBuildImpl(): Promise<number> { ...@@ -117,6 +130,7 @@ async function webpackBuildImpl(): Promise<number> {
}) })
const clientConfig = configs[0] const clientConfig = configs[0]
const serverConfig = configs[1]
if ( if (
clientConfig.optimization && clientConfig.optimization &&
...@@ -141,7 +155,7 @@ async function webpackBuildImpl(): Promise<number> { ...@@ -141,7 +155,7 @@ async function webpackBuildImpl(): Promise<number> {
// injected to this set and then will be consumed by the client compiler. // injected to this set and then will be consumed by the client compiler.
injectedClientEntries.clear() injectedClientEntries.clear()
const serverResult = await runCompiler(configs[1], { const serverResult = await runCompiler(serverConfig, {
runWebpackSpan, runWebpackSpan,
}) })
const edgeServerResult = configs[2] const edgeServerResult = configs[2]
...@@ -206,6 +220,10 @@ async function webpackBuildImpl(): Promise<number> { ...@@ -206,6 +220,10 @@ async function webpackBuildImpl(): Promise<number> {
clientConfig as webpack.Configuration clientConfig as webpack.Configuration
).plugins?.find(isTelemetryPlugin) ).plugins?.find(isTelemetryPlugin)
const traceEntryPointsPlugin = (
serverConfig as webpack.Configuration
).plugins?.find(isTraceEntryPointsPlugin)
const webpackBuildEnd = process.hrtime(webpackBuildStart) const webpackBuildEnd = process.hrtime(webpackBuildStart)
if (buildSpinner) { if (buildSpinner) {
buildSpinner.stopAndPersist() buildSpinner.stopAndPersist()
...@@ -257,7 +275,10 @@ async function webpackBuildImpl(): Promise<number> { ...@@ -257,7 +275,10 @@ async function webpackBuildImpl(): Promise<number> {
} else { } else {
Log.info('Compiled successfully') Log.info('Compiled successfully')
} }
return webpackBuildEnd[0] return {
duration: webpackBuildEnd[0],
turbotraceContext: traceEntryPointsPlugin?.turbotraceContext,
}
} }
} }
...@@ -279,7 +300,19 @@ async function workerMain() { ...@@ -279,7 +300,19 @@ async function workerMain() {
try { try {
const result = await webpackBuildImpl() const result = await webpackBuildImpl()
parentPort!.postMessage(result) const { entriesTrace } = result.turbotraceContext ?? {}
if (entriesTrace) {
const { entryNameMap, depModArray } = entriesTrace
if (depModArray) {
result.turbotraceContext!.entriesTrace!.depModArray = depModArray
}
if (entryNameMap) {
const entryEntries = Array.from(entryNameMap?.entries() ?? [])
// @ts-expect-error
result.turbotraceContext.entriesTrace.entryNameMap = entryEntries
}
}
parentPort!.postMessage(JSON.stringify(result))
} catch (e) { } catch (e) {
parentPort!.postMessage(e) parentPort!.postMessage(e)
} finally { } finally {
...@@ -305,17 +338,35 @@ async function webpackBuildWithWorker() { ...@@ -305,17 +338,35 @@ async function webpackBuildWithWorker() {
}, },
}) })
const result = await new Promise((resolve, reject) => { const result = JSON.parse(
worker.on('message', resolve) await new Promise((resolve, reject) => {
worker.on('error', reject) worker.on('message', (data) => {
worker.on('exit', (code) => { if (data instanceof Error) {
if (code !== 0) { reject(data)
reject(new Error(`Worker stopped with exit code ${code}`)) } else {
} resolve(data)
}
})
worker.on('error', reject)
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
}) })
}) ) as {
duration: number
turbotraceContext?: TurbotraceContext
}
if (result.turbotraceContext?.entriesTrace) {
const { entryNameMap } = result.turbotraceContext.entriesTrace
if (entryNameMap) {
result.turbotraceContext.entriesTrace.entryNameMap = new Map(entryNameMap)
}
}
return result as number return result
} }
export async function webpackBuild() { export async function webpackBuild() {
......
...@@ -481,15 +481,9 @@ const configSchema = { ...@@ -481,15 +481,9 @@ const configSchema = {
processCwd: { processCwd: {
type: 'string', type: 'string',
}, },
maxFiles: {
type: 'integer',
},
memoryLimit: { memoryLimit: {
type: 'integer', type: 'integer',
}, },
skipEntries: {
type: 'boolean',
},
}, },
}, },
}, },
......
...@@ -206,9 +206,8 @@ export interface ExperimentalConfig { ...@@ -206,9 +206,8 @@ export interface ExperimentalConfig {
logAll?: boolean logAll?: boolean
contextDirectory?: string contextDirectory?: string
processCwd?: string processCwd?: string
maxFiles?: number /** in `MB` */
memoryLimit?: number memoryLimit?: number
skipEntries?: boolean
} }
mdxRs?: boolean mdxRs?: boolean
/** /**
......
...@@ -508,7 +508,7 @@ importers: ...@@ -508,7 +508,7 @@ importers:
'@babel/types': 7.18.0 '@babel/types': 7.18.0
'@edge-runtime/primitives': 2.0.0 '@edge-runtime/primitives': 2.0.0
'@hapi/accept': 5.0.2 '@hapi/accept': 5.0.2
'@napi-rs/cli': 2.13.3 '@napi-rs/cli': 2.14.7
'@napi-rs/triples': 1.1.0 '@napi-rs/triples': 1.1.0
'@next/env': 13.1.7-canary.8 '@next/env': 13.1.7-canary.8
'@next/polyfill-module': 13.1.7-canary.8 '@next/polyfill-module': 13.1.7-canary.8
...@@ -718,7 +718,7 @@ importers: ...@@ -718,7 +718,7 @@ importers:
'@babel/types': 7.18.0 '@babel/types': 7.18.0
'@edge-runtime/primitives': 2.0.0 '@edge-runtime/primitives': 2.0.0
'@hapi/accept': 5.0.2 '@hapi/accept': 5.0.2
'@napi-rs/cli': 2.13.3 '@napi-rs/cli': 2.14.7
'@napi-rs/triples': 1.1.0 '@napi-rs/triples': 1.1.0
'@next/polyfill-module': link:../next-polyfill-module '@next/polyfill-module': link:../next-polyfill-module
'@next/polyfill-nomodule': link:../next-polyfill-nomodule '@next/polyfill-nomodule': link:../next-polyfill-nomodule
...@@ -961,9 +961,9 @@ importers: ...@@ -961,9 +961,9 @@ importers:
packages/next-swc: packages/next-swc:
specifiers: specifiers:
'@napi-rs/cli': 2.13.3 '@napi-rs/cli': 2.14.7
devDependencies: devDependencies:
'@napi-rs/cli': 2.13.3 '@napi-rs/cli': 2.14.7
packages/react-dev-overlay: packages/react-dev-overlay:
specifiers: specifiers:
...@@ -5912,8 +5912,8 @@ packages: ...@@ -5912,8 +5912,8 @@ packages:
glob-to-regexp: 0.3.0 glob-to-regexp: 0.3.0
dev: true dev: true
/@napi-rs/cli/2.13.3: /@napi-rs/cli/2.14.7:
resolution: {integrity: sha512-nAlbKuakQ+YHZE+M3Afih9UA1jr+gx63Gt4xHA+j2xD1NY6TjQ+QCgF9Yaj/YZIkCc2t3CZh52znFrfbU8b2bA==} resolution: {integrity: sha512-H+YCgdbBNMWn8c878C3RsRYcMxamWI7rB0H+1TqOy9n6u31isikcRyW1VDyoNHp7ApfmzV0+tpPopVi0W7WHAA==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
hasBin: true hasBin: true
dev: true dev: true
......
...@@ -6,8 +6,7 @@ import { nextBuild } from 'next-test-utils' ...@@ -6,8 +6,7 @@ import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../app') const appDir = join(__dirname, '../app')
// TODO: investigate failure from incorrect exit code describe('build trace with extra entries', () => {
describe.skip('build trace with extra entries', () => {
it('should build and trace correctly', async () => { it('should build and trace correctly', async () => {
const result = await nextBuild(appDir, undefined, { const result = await nextBuild(appDir, undefined, {
cwd: appDir, cwd: appDir,
......
import fs from 'fs'
import path from 'path'
const getCmsData = require('some-cms')
try {
fs.readdirSync(path.join(process.cwd(), 'public/exclude-me'))
} catch (_) {}
export function fetchData() {
return getCmsData()
}
import fs from 'fs'
import path from 'path'
export function getData() {
return JSON.parse(
fs.readFileSync(path.join(process.cwd(), 'content/hello.json'), 'utf8')
)
}
const path = require('path')
module.exports = {
webpack(cfg, { isServer, nextRuntime }) {
console.log(cfg.entry)
const origEntry = cfg.entry
cfg.entry = async () => {
const origEntries = await origEntry()
if (isServer && nextRuntime === 'nodejs') {
const curEntry = origEntries['pages/_app']
origEntries['pages/_app'] = [
path.join(__dirname, 'lib/get-data.js'),
...curEntry,
]
console.log(origEntries)
}
return origEntries
}
return cfg
},
experimental: {
turbotrace: {
contextDirectory: path.join(__dirname, '..', '..', '..', '..'),
memoryLimit: 4096,
},
webpackBuildWorker: true,
},
}
function getCmsData() {
return 'hello'
}
module.exports = getCmsData
import 'nested-structure/constants'
export default function Page() {
return <p>another page</p>
}
export function getStaticProps() {
return {
props: {},
}
}
import fs from 'fs'
import path from 'path'
import Image from 'next/image'
import testImage from '../public/test.jpg'
export default function Page(props) {
return (
<div>
<Image src={testImage} placeholder="blur" alt="test" />
</div>
)
}
export function getServerSideProps() {
try {
// this should be included in the trace since it's not an
// import
fs.readFileSync(path.join(process.cwd(), 'public/another.jpg'))
} catch (_) {}
return {
props: {},
}
}
import { fetchData } from '../lib/fetch-data'
export const config = {
unstable_includeFiles: ['include-me/*'],
unstable_excludeFiles: ['public/exclude-me/**/*'],
}
export default function Page() {
return 'index page'
}
export function getStaticProps() {
fetchData()
return {
props: {},
}
}
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../app')
describe('build trace with extra entries', () => {
it('should build and trace correctly', async () => {
const result = await nextBuild(appDir, undefined, {
cwd: appDir,
stderr: true,
stdout: true,
})
console.log(result)
expect(result.code).toBe(0)
const appTrace = await fs.readJSON(
join(appDir, '.next/server/pages/_app.js.nft.json')
)
const indexTrace = await fs.readJSON(
join(appDir, '.next/server/pages/index.js.nft.json')
)
const anotherTrace = await fs.readJSON(
join(appDir, '.next/server/pages/another.js.nft.json')
)
const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json')
)
const tracedFiles = [
...appTrace.files,
...indexTrace.files,
...anotherTrace.files,
...imageTrace.files,
]
expect(tracedFiles.some((file) => file.endsWith('hello.json'))).toBe(true)
expect(tracedFiles.some((file) => file.includes('some-cms/index.js'))).toBe(
true
)
expect(
tracedFiles.some((file) => file === '../../../include-me/hello.txt')
).toBe(true)
expect(
tracedFiles.some((file) => file === '../../../include-me/second.txt')
).toBe(true)
expect(indexTrace.files.some((file) => file.includes('exclude-me'))).toBe(
false
)
expect(
tracedFiles.some((file) =>
file.includes('nested-structure/constants/package.json')
)
).toBe(true)
expect(
tracedFiles.some((file) => file.includes('nested-structure/package.json'))
).toBe(true)
expect(
tracedFiles.some((file) =>
file.includes('nested-structure/lib/constants.js')
)
).toBe(true)
expect(
tracedFiles.some((file) => file.includes('public/another.jpg'))
).toBe(true)
expect(tracedFiles.some((file) => file.includes('public/test.jpg'))).toBe(
false
)
})
})
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