Unverified Commit 3bd112b5 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Turbopack: Implement build worker (#75391)

## What?

Runs Turbopack in a separate child process so that e.g. memory usage can
be cleaned up before continuing with the rest of the Next.js build. This
will lower the peak memory consumption given that before this change the
Turbopack cache was kept around until the end of the build.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 88cdbae6
...@@ -1389,7 +1389,7 @@ export default async function build( ...@@ -1389,7 +1389,7 @@ export default async function build(
duration: compilerDuration, duration: compilerDuration,
shutdownPromise: p, shutdownPromise: p,
...rest ...rest
} = await turbopackBuild(false) } = await turbopackBuild(true)
shutdownPromise = p shutdownPromise = p
traceMemoryUsage('Finished build', nextBuildSpan) traceMemoryUsage('Finished build', nextBuildSpan)
......
...@@ -20,6 +20,11 @@ import { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loa ...@@ -20,6 +20,11 @@ import { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loa
import { createProgress } from '../progress' import { createProgress } from '../progress'
import * as Log from '../output/log' import * as Log from '../output/log'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'
import loadConfig from '../../server/config'
import { hasCustomExportOutput } from '../../export/utils'
import { Telemetry } from '../../telemetry/storage'
import { setGlobal } from '../../trace'
const IS_TURBOPACK_BUILD = process.env.TURBOPACK && process.env.TURBOPACK_BUILD const IS_TURBOPACK_BUILD = process.env.TURBOPACK && process.env.TURBOPACK_BUILD
...@@ -298,3 +303,32 @@ export async function turbopackBuild(): Promise<{ ...@@ -298,3 +303,32 @@ export async function turbopackBuild(): Promise<{
shutdownPromise, shutdownPromise,
} }
} }
export async function workerMain(workerData: {
buildContext: typeof NextBuildContext
}): Promise<Awaited<ReturnType<typeof turbopackBuild>>> {
// setup new build context from the serialized data passed from the parent
Object.assign(NextBuildContext, workerData.buildContext)
/// load the config because it's not serializable
NextBuildContext.config = await loadConfig(
PHASE_PRODUCTION_BUILD,
NextBuildContext.dir!
)
// Matches handling in build/index.ts
// https://github.com/vercel/next.js/blob/84f347fc86f4efc4ec9f13615c215e4b9fb6f8f0/packages/next/src/build/index.ts#L815-L818
// Ensures the `config.distDir` option is matched.
if (hasCustomExportOutput(NextBuildContext.config)) {
NextBuildContext.config.distDir = '.next'
}
// Clone the telemetry for worker
const telemetry = new Telemetry({
distDir: NextBuildContext.config.distDir,
})
setGlobal('telemetry', telemetry)
const result = await turbopackBuild()
return result
}
import path from 'path'
import {
formatNodeOptions,
getParsedNodeOptionsWithoutInspect,
} from '../../server/lib/utils'
import { Worker } from '../../lib/worker'
import { NextBuildContext } from '../build-context'
async function turbopackBuildWithWorker() {
const nodeOptions = getParsedNodeOptionsWithoutInspect()
try {
const worker = new Worker(path.join(__dirname, 'impl.js'), {
exposedMethods: ['workerMain'],
numWorkers: 1,
maxRetries: 0,
forkOptions: {
env: {
...process.env,
NEXT_PRIVATE_BUILD_WORKER: '1',
NODE_OPTIONS: formatNodeOptions(nodeOptions),
},
},
}) as Worker & typeof import('./impl')
const { nextBuildSpan, ...prunedBuildContext } = NextBuildContext
const result = await worker.workerMain({
buildContext: prunedBuildContext,
})
// destroy worker so it's not sticking around using memory
await worker.end()
return result
} catch (err: any) {
// When the error is a serialized `Error` object we need to recreate the `Error` instance
// in order to keep the consistent error reporting behavior.
if (err.type === 'Error') {
const error = new Error(err.message)
if (err.name) {
error.name = err.name
}
if (err.cause) {
error.cause = err.cause
}
error.message = err.message
error.stack = err.stack
throw error
}
throw err
}
}
export function turbopackBuild( export function turbopackBuild(
withWorker: boolean withWorker: boolean
): ReturnType<typeof import('./impl').turbopackBuild> { ): ReturnType<typeof import('./impl').turbopackBuild> {
if (withWorker) { if (withWorker) {
// TODO implement worker in follow-up PR. return turbopackBuildWithWorker()
const build = (require('./impl') as typeof import('./impl')).turbopackBuild
return build()
} else { } else {
const build = (require('./impl') as typeof import('./impl')).turbopackBuild const build = (require('./impl') as typeof import('./impl')).turbopackBuild
return build() return build()
......
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