Commit 6ff089f8 authored by Tim Neutkens's avatar Tim Neutkens Committed by Janka Uryga

Speed up createNext test suite isolation (#64909)

Before: 25.71s

![CleanShot 2024-04-23 at 12 19
42@2x](https://github.com/vercel/next.js/assets/6324199/3a0ebb81-ac55-4b0c-8bfc-9a61ce138e6f)

After: 11.05s (-57%)

![CleanShot 2024-04-23 at 12 16
35@2x](https://github.com/vercel/next.js/assets/6324199/d7b6cd4c-d1e4-4dc2-a423-20b539186d25)

Currently the system for isolation looks like this:

- Copy `packages` folder to an isolated directory
- Run `pnpm pack` for all folders in `packages`
- Collect the pack files, add them as `dependencies` in package.json of
the isolated application
- Run `pnpm install`

Because the `next-swc` (Turbopack + SWC, yes we still need to rename the
package) binary file is quite large in development (900MB+) it means we
have to copy, then zip (pnpm pack), then unzip (pnpm install) that
binary, which takes about 3+ seconds in each step.

The change in this PR is to skip the copy/zip/unzip completely by
providing the folder path for the binary directly to Next.js, as it's a
binary we don't need the special isolation for this, it's already
standalone so running it directly allows us to skip 14,6 seconds of work
that is required for each isolated test in development.

This will likely have little effect on CI times as we already do some
tricks like only running the packing at the start of the CI process.
Only thing that could be better and is probably worth doing is adopting
this change for the time it saves for unzipping, that's almost 4 seconds
per test still.

<!-- 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:

- 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

- 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

- 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

- 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

- 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

Closes NEXT-
Fixes #

-->

Closes NEXT-3200

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 8fe7ec14
...@@ -5,6 +5,12 @@ const exec = require('../util/exec') ...@@ -5,6 +5,12 @@ const exec = require('../util/exec')
const logger = require('../util/logger') const logger = require('../util/logger')
const execa = require('execa') const execa = require('execa')
const mockSpan = () => ({
traceAsyncFn: (fn) => fn(mockTrace()),
traceFn: (fn) => fn(mockTrace()),
traceChild: () => mockTrace(),
})
module.exports = (actionInfo) => { module.exports = (actionInfo) => {
return { return {
async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') { async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') {
...@@ -59,7 +65,11 @@ module.exports = (actionInfo) => { ...@@ -59,7 +65,11 @@ module.exports = (actionInfo) => {
* @param {{ repoDir: string, nextSwcVersion: null | string }} options Required options * @param {{ repoDir: string, nextSwcVersion: null | string }} options Required options
* @returns {Promise<Map<string, string>>} List packages key is the package name, value is the path to the packed tar file.' * @returns {Promise<Map<string, string>>} List packages key is the package name, value is the path to the packed tar file.'
*/ */
async linkPackages({ repoDir, nextSwcVersion }) { async linkPackages({ repoDir, nextSwcVersion, parentSpan }) {
if (!parentSpan) {
// Not all callers provide a parent span
parentSpan = mockSpan()
}
/** @type {Map<string, string>} */ /** @type {Map<string, string>} */
const pkgPaths = new Map() const pkgPaths = new Map()
/** @type {Map<string, { packageJsonPath: string, packagePath: string, packageJson: any, packedPackageTarPath: string }>} */ /** @type {Map<string, { packageJsonPath: string, packagePath: string, packageJson: any, packedPackageTarPath: string }>} */
...@@ -68,8 +78,10 @@ module.exports = (actionInfo) => { ...@@ -68,8 +78,10 @@ module.exports = (actionInfo) => {
let packageFolders let packageFolders
try { try {
packageFolders = await fs.promises.readdir( packageFolders = await parentSpan
path.join(repoDir, 'packages') .traceChild('read-packages-folder')
.traceAsyncFn(() =>
fs.promises.readdir(path.join(repoDir, 'packages'))
) )
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
...@@ -79,6 +91,7 @@ module.exports = (actionInfo) => { ...@@ -79,6 +91,7 @@ module.exports = (actionInfo) => {
throw err throw err
} }
parentSpan.traceChild('get-pkgdatas').traceFn(() => {
for (const packageFolder of packageFolders) { for (const packageFolder of packageFolders) {
const packagePath = path.join(repoDir, 'packages', packageFolder) const packagePath = path.join(repoDir, 'packages', packageFolder)
const packedPackageTarPath = path.join( const packedPackageTarPath = path.join(
...@@ -103,7 +116,11 @@ module.exports = (actionInfo) => { ...@@ -103,7 +116,11 @@ module.exports = (actionInfo) => {
}) })
pkgPaths.set(packageName, packedPackageTarPath) pkgPaths.set(packageName, packedPackageTarPath)
} }
})
await parentSpan
.traceChild('write-packagejson')
.traceAsyncFn(async () => {
for (const [ for (const [
packageName, packageName,
{ packageJsonPath, packagePath, packageJson }, { packageJsonPath, packagePath, packageJson },
...@@ -131,7 +148,9 @@ module.exports = (actionInfo) => { ...@@ -131,7 +148,9 @@ module.exports = (actionInfo) => {
try { try {
const swcBinariesDirContents = ( const swcBinariesDirContents = (
await fs.promises.readdir(path.join(packagePath, 'native')) await fs.promises.readdir(path.join(packagePath, 'native'))
).filter((file) => file !== '.gitignore' && file !== 'index.d.ts') ).filter(
(file) => file !== '.gitignore' && file !== 'index.d.ts'
)
require('console').log( require('console').log(
'using swc binaries: ', 'using swc binaries: ',
...@@ -155,10 +174,6 @@ module.exports = (actionInfo) => { ...@@ -155,10 +174,6 @@ module.exports = (actionInfo) => {
'@next/swc-linux-x64-gnu': nextSwcVersion, '@next/swc-linux-x64-gnu': nextSwcVersion,
}) })
} else { } else {
if (nextSwcPkg) {
packageJson.dependencies['@next/swc'] =
nextSwcPkg.packedPackageTarPath
}
} }
} }
...@@ -168,7 +183,11 @@ module.exports = (actionInfo) => { ...@@ -168,7 +183,11 @@ module.exports = (actionInfo) => {
'utf8' 'utf8'
) )
} }
})
await parentSpan
.traceChild('pnpm-packing')
.traceAsyncFn(async (packingSpan) => {
// wait to pack packages until after dependency paths have been updated // wait to pack packages until after dependency paths have been updated
// to the correct versions // to the correct versions
await Promise.all( await Promise.all(
...@@ -177,6 +196,9 @@ module.exports = (actionInfo) => { ...@@ -177,6 +196,9 @@ module.exports = (actionInfo) => {
packageName, packageName,
{ packagePath: pkgPath, packedPackageTarPath: packedPkgPath }, { packagePath: pkgPath, packedPackageTarPath: packedPkgPath },
]) => { ]) => {
return packingSpan
.traceChild('handle-package', { packageName })
.traceAsyncFn(async (handlePackageSpan) => {
/** @type {null | () => Promise<void>} */ /** @type {null | () => Promise<void>} */
let cleanup = null let cleanup = null
...@@ -196,10 +218,14 @@ module.exports = (actionInfo) => { ...@@ -196,10 +218,14 @@ module.exports = (actionInfo) => {
'disabled-native-gitignore' 'disabled-native-gitignore'
) )
await fs.promises.rename( await handlePackageSpan
.traceChild('rename-gitignore')
.traceAsyncFn(() =>
fs.promises.rename(
nativeGitignorePath, nativeGitignorePath,
renamedGitignorePath renamedGitignorePath
) )
)
cleanup = async () => { cleanup = async () => {
await fs.promises.rename( await fs.promises.rename(
renamedGitignorePath, renamedGitignorePath,
...@@ -217,24 +243,34 @@ module.exports = (actionInfo) => { ...@@ -217,24 +243,34 @@ module.exports = (actionInfo) => {
} }
let execResult let execResult
try { try {
execResult = await execa('pnpm', ['pack'], options) execResult = await handlePackageSpan
.traceChild('pnpm-pack-try-1')
.traceAsyncFn(() => execa('pnpm', ['pack'], options))
} catch { } catch {
execResult = await execa('pnpm', ['pack'], options) execResult = await handlePackageSpan
.traceChild('pnpm-pack-try-2')
.traceAsyncFn(() => execa('pnpm', ['pack'], options))
} }
const { stdout } = execResult const { stdout } = execResult
const packedFileName = stdout.trim() const packedFileName = stdout.trim()
await Promise.all([ await handlePackageSpan
.traceChild('rename-packed-tar-and-cleanup')
.traceAsyncFn(() =>
Promise.all([
fs.promises.rename( fs.promises.rename(
path.join(pkgPath, packedFileName), path.join(pkgPath, packedFileName),
packedPkgPath packedPkgPath
), ),
cleanup?.(), cleanup?.(),
]) ])
)
})
} }
) )
) )
})
return pkgPaths return pkgPaths
}, },
......
...@@ -1329,13 +1329,25 @@ function loadNative(importPath?: string) { ...@@ -1329,13 +1329,25 @@ function loadNative(importPath?: string) {
let bindings: any let bindings: any
let attempts: any[] = [] let attempts: any[] = []
const NEXT_TEST_NATIVE_DIR = process.env.NEXT_TEST_NATIVE_DIR
for (const triple of triples) { for (const triple of triples) {
if (NEXT_TEST_NATIVE_DIR) {
try {
// Use the binary directly to skip `pnpm pack` for testing as it's slow because of the large native binary.
bindings = require(`${NEXT_TEST_NATIVE_DIR}/next-swc.${triple.platformArchABI}.node`)
console.log(
'next-swc build: local built @next/swc from NEXT_TEST_NATIVE_DIR'
)
break
} catch (e) {}
} else {
try { try {
bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`) bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`)
infoLog('next-swc build: local built @next/swc') console.log('next-swc build: local built @next/swc')
break break
} catch (e) {} } catch (e) {}
} }
}
if (!bindings) { if (!bindings) {
for (const triple of triples) { for (const triple of triples) {
......
...@@ -80,6 +80,7 @@ const testFilters = { ...@@ -80,6 +80,7 @@ const testFilters = {
const mockTrace = () => ({ const mockTrace = () => ({
traceAsyncFn: (fn) => fn(mockTrace()), traceAsyncFn: (fn) => fn(mockTrace()),
traceFn: (fn) => fn(mockTrace()),
traceChild: () => mockTrace(), traceChild: () => mockTrace(),
}) })
......
...@@ -80,7 +80,7 @@ async function createNextInstall({ ...@@ -80,7 +80,7 @@ async function createNextInstall({
!item.includes('pnpm-lock.yaml') && !item.includes('pnpm-lock.yaml') &&
!item.includes('.DS_Store') && !item.includes('.DS_Store') &&
// Exclude Rust compilation files // Exclude Rust compilation files
!/next-swc[\\/]target/.test(item) !/packages[\\/]next-swc/.test(item)
) )
}, },
} }
...@@ -88,42 +88,27 @@ async function createNextInstall({ ...@@ -88,42 +88,27 @@ async function createNextInstall({
) )
} }
await rootSpan const nativePath = path.join(origRepoDir, 'packages/next-swc/native')
.traceChild('ensure swc binary')
.traceAsyncFn(async () => { const hasNativeBinary = fs
// ensure swc binary is present in the native folder if .readdirSync(nativePath)
// not already built .some((item) => item.endsWith('.node'))
for (const folder of await fs.readdir(
path.join(origRepoDir, 'node_modules/@next') if (hasNativeBinary) {
)) { process.env.NEXT_TEST_NATIVE_DIR = nativePath
if (folder.startsWith('swc-')) { } else {
const swcPkgPath = path.join( const swcDirectory = fs
origRepoDir, .readdirSync(path.join(origRepoDir, 'node_modules/@next'))
'node_modules/@next', .find((directory) => directory.startsWith('swc-'))
folder process.env.NEXT_TEST_NATIVE_DIR = swcDirectory
)
const outputPath = path.join(
tmpRepoDir,
'packages/next-swc/native'
)
await fs.copy(swcPkgPath, outputPath, {
filter: (item) => {
return (
item === swcPkgPath ||
(item.endsWith('.node') &&
!fs.pathExistsSync(
path.join(outputPath, path.basename(item))
))
)
},
})
}
} }
})
pkgPaths = await rootSpan.traceChild('linkPackages').traceAsyncFn(() => pkgPaths = await rootSpan
.traceChild('linkPackages')
.traceAsyncFn((span) =>
linkPackages({ linkPackages({
repoDir: tmpRepoDir, repoDir: tmpRepoDir,
parentSpan: span,
}) })
) )
} }
...@@ -170,7 +155,7 @@ async function createNextInstall({ ...@@ -170,7 +155,7 @@ async function createNextInstall({
}) })
} else { } else {
await rootSpan await rootSpan
.traceChild('run generic install command') .traceChild('run generic install command', combinedDependencies)
.traceAsyncFn(() => installDependencies(installDir, tmpDir)) .traceAsyncFn(() => installDependencies(installDir, tmpDir))
} }
......
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