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')
const logger = require('../util/logger')
const execa = require('execa')
const mockSpan = () => ({
traceAsyncFn: (fn) => fn(mockTrace()),
traceFn: (fn) => fn(mockTrace()),
traceChild: () => mockTrace(),
})
module.exports = (actionInfo) => {
return {
async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') {
......@@ -59,7 +65,11 @@ module.exports = (actionInfo) => {
* @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.'
*/
async linkPackages({ repoDir, nextSwcVersion }) {
async linkPackages({ repoDir, nextSwcVersion, parentSpan }) {
if (!parentSpan) {
// Not all callers provide a parent span
parentSpan = mockSpan()
}
/** @type {Map<string, string>} */
const pkgPaths = new Map()
/** @type {Map<string, { packageJsonPath: string, packagePath: string, packageJson: any, packedPackageTarPath: string }>} */
......@@ -68,9 +78,11 @@ module.exports = (actionInfo) => {
let packageFolders
try {
packageFolders = await fs.promises.readdir(
path.join(repoDir, 'packages')
)
packageFolders = await parentSpan
.traceChild('read-packages-folder')
.traceAsyncFn(() =>
fs.promises.readdir(path.join(repoDir, 'packages'))
)
} catch (err) {
if (err.code === 'ENOENT') {
require('console').log('no packages to link')
......@@ -79,162 +91,186 @@ module.exports = (actionInfo) => {
throw err
}
for (const packageFolder of packageFolders) {
const packagePath = path.join(repoDir, 'packages', packageFolder)
const packedPackageTarPath = path.join(
packagePath,
`${packageFolder}-packed.tgz`
)
const packageJsonPath = path.join(packagePath, 'package.json')
if (!existsSync(packageJsonPath)) {
require('console').log(`Skipping ${packageFolder}, no package.json`)
continue
}
parentSpan.traceChild('get-pkgdatas').traceFn(() => {
for (const packageFolder of packageFolders) {
const packagePath = path.join(repoDir, 'packages', packageFolder)
const packedPackageTarPath = path.join(
packagePath,
`${packageFolder}-packed.tgz`
)
const packageJsonPath = path.join(packagePath, 'package.json')
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath))
const { name: packageName } = packageJson
if (!existsSync(packageJsonPath)) {
require('console').log(`Skipping ${packageFolder}, no package.json`)
continue
}
pkgDatas.set(packageName, {
packageJsonPath,
packagePath,
packageJson,
packedPackageTarPath,
})
pkgPaths.set(packageName, packedPackageTarPath)
}
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath))
const { name: packageName } = packageJson
for (const [
packageName,
{ packageJsonPath, packagePath, packageJson },
] of pkgDatas.entries()) {
// This loops through all items to get the packagedPkgPath of each item and add it to pkgData.dependencies
for (const [
packageName,
{ packedPackageTarPath },
] of pkgDatas.entries()) {
if (
!packageJson.dependencies ||
!packageJson.dependencies[packageName]
)
continue
// Edit the pkgData of the current item to point to the packed tgz
packageJson.dependencies[packageName] = packedPackageTarPath
pkgDatas.set(packageName, {
packageJsonPath,
packagePath,
packageJson,
packedPackageTarPath,
})
pkgPaths.set(packageName, packedPackageTarPath)
}
})
// make sure native binaries are included in local linking
if (packageName === '@next/swc') {
packageJson.files ||= []
await parentSpan
.traceChild('write-packagejson')
.traceAsyncFn(async () => {
for (const [
packageName,
{ packageJsonPath, packagePath, packageJson },
] of pkgDatas.entries()) {
// This loops through all items to get the packagedPkgPath of each item and add it to pkgData.dependencies
for (const [
packageName,
{ packedPackageTarPath },
] of pkgDatas.entries()) {
if (
!packageJson.dependencies ||
!packageJson.dependencies[packageName]
)
continue
// Edit the pkgData of the current item to point to the packed tgz
packageJson.dependencies[packageName] = packedPackageTarPath
}
packageJson.files.push('native')
// make sure native binaries are included in local linking
if (packageName === '@next/swc') {
packageJson.files ||= []
try {
const swcBinariesDirContents = (
await fs.promises.readdir(path.join(packagePath, 'native'))
).filter((file) => file !== '.gitignore' && file !== 'index.d.ts')
packageJson.files.push('native')
require('console').log(
'using swc binaries: ',
swcBinariesDirContents.join(', ')
)
} catch (err) {
if (err.code === 'ENOENT') {
require('console').log('swc binaries dir is missing!')
}
throw err
}
} else if (packageName === 'next') {
const nextSwcPkg = pkgDatas.get('@next/swc')
try {
const swcBinariesDirContents = (
await fs.promises.readdir(path.join(packagePath, 'native'))
).filter(
(file) => file !== '.gitignore' && file !== 'index.d.ts'
)
console.log('using swc dep', {
nextSwcVersion,
nextSwcPkg,
})
if (nextSwcVersion) {
Object.assign(packageJson.dependencies, {
'@next/swc-linux-x64-gnu': nextSwcVersion,
})
} else {
if (nextSwcPkg) {
packageJson.dependencies['@next/swc'] =
nextSwcPkg.packedPackageTarPath
require('console').log(
'using swc binaries: ',
swcBinariesDirContents.join(', ')
)
} catch (err) {
if (err.code === 'ENOENT') {
require('console').log('swc binaries dir is missing!')
}
throw err
}
} else if (packageName === 'next') {
const nextSwcPkg = pkgDatas.get('@next/swc')
console.log('using swc dep', {
nextSwcVersion,
nextSwcPkg,
})
if (nextSwcVersion) {
Object.assign(packageJson.dependencies, {
'@next/swc-linux-x64-gnu': nextSwcVersion,
})
} else {
}
}
await fs.promises.writeFile(
packageJsonPath,
JSON.stringify(packageJson, null, 2),
'utf8'
)
}
}
})
await fs.promises.writeFile(
packageJsonPath,
JSON.stringify(packageJson, null, 2),
'utf8'
)
}
await parentSpan
.traceChild('pnpm-packing')
.traceAsyncFn(async (packingSpan) => {
// wait to pack packages until after dependency paths have been updated
// to the correct versions
await Promise.all(
Array.from(pkgDatas.entries()).map(
async ([
packageName,
{ packagePath: pkgPath, packedPackageTarPath: packedPkgPath },
]) => {
return packingSpan
.traceChild('handle-package', { packageName })
.traceAsyncFn(async (handlePackageSpan) => {
/** @type {null | () => Promise<void>} */
let cleanup = null
// wait to pack packages until after dependency paths have been updated
// to the correct versions
await Promise.all(
Array.from(pkgDatas.entries()).map(
async ([
packageName,
{ packagePath: pkgPath, packedPackageTarPath: packedPkgPath },
]) => {
/** @type {null | () => Promise<void>} */
let cleanup = null
if (packageName === '@next/swc') {
// next-swc uses a gitignore to prevent the committing of native builds but it doesn't
// use files in package.json because it publishes to individual packages based on architecture.
// When we used yarn to pack these packages the gitignore was ignored so the native builds were packed
// however npm does respect gitignore when packing so we need to remove it in this specific case
// to ensure the native builds are packed for use in gh actions and related scripts
if (packageName === '@next/swc') {
// next-swc uses a gitignore to prevent the committing of native builds but it doesn't
// use files in package.json because it publishes to individual packages based on architecture.
// When we used yarn to pack these packages the gitignore was ignored so the native builds were packed
// however npm does respect gitignore when packing so we need to remove it in this specific case
// to ensure the native builds are packed for use in gh actions and related scripts
const nativeGitignorePath = path.join(
pkgPath,
'native/.gitignore'
)
const renamedGitignorePath = path.join(
pkgPath,
'disabled-native-gitignore'
)
const nativeGitignorePath = path.join(
pkgPath,
'native/.gitignore'
)
const renamedGitignorePath = path.join(
pkgPath,
'disabled-native-gitignore'
)
await fs.promises.rename(
nativeGitignorePath,
renamedGitignorePath
)
cleanup = async () => {
await fs.promises.rename(
renamedGitignorePath,
nativeGitignorePath
)
}
}
await handlePackageSpan
.traceChild('rename-gitignore')
.traceAsyncFn(() =>
fs.promises.rename(
nativeGitignorePath,
renamedGitignorePath
)
)
cleanup = async () => {
await fs.promises.rename(
renamedGitignorePath,
nativeGitignorePath
)
}
}
const options = {
cwd: pkgPath,
env: {
...process.env,
COREPACK_ENABLE_STRICT: '0',
},
}
let execResult
try {
execResult = await execa('pnpm', ['pack'], options)
} catch {
execResult = await execa('pnpm', ['pack'], options)
}
const { stdout } = execResult
const options = {
cwd: pkgPath,
env: {
...process.env,
COREPACK_ENABLE_STRICT: '0',
},
}
let execResult
try {
execResult = await handlePackageSpan
.traceChild('pnpm-pack-try-1')
.traceAsyncFn(() => execa('pnpm', ['pack'], options))
} catch {
execResult = await handlePackageSpan
.traceChild('pnpm-pack-try-2')
.traceAsyncFn(() => execa('pnpm', ['pack'], options))
}
const { stdout } = execResult
const packedFileName = stdout.trim()
const packedFileName = stdout.trim()
await Promise.all([
fs.promises.rename(
path.join(pkgPath, packedFileName),
packedPkgPath
),
cleanup?.(),
])
}
)
)
await handlePackageSpan
.traceChild('rename-packed-tar-and-cleanup')
.traceAsyncFn(() =>
Promise.all([
fs.promises.rename(
path.join(pkgPath, packedFileName),
packedPkgPath
),
cleanup?.(),
])
)
})
}
)
)
})
return pkgPaths
},
......
......@@ -1329,12 +1329,24 @@ function loadNative(importPath?: string) {
let bindings: any
let attempts: any[] = []
const NEXT_TEST_NATIVE_DIR = process.env.NEXT_TEST_NATIVE_DIR
for (const triple of triples) {
try {
bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`)
infoLog('next-swc build: local built @next/swc')
break
} catch (e) {}
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 {
bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`)
console.log('next-swc build: local built @next/swc')
break
} catch (e) {}
}
}
if (!bindings) {
......
......@@ -80,6 +80,7 @@ const testFilters = {
const mockTrace = () => ({
traceAsyncFn: (fn) => fn(mockTrace()),
traceFn: (fn) => fn(mockTrace()),
traceChild: () => mockTrace(),
})
......
......@@ -80,7 +80,7 @@ async function createNextInstall({
!item.includes('pnpm-lock.yaml') &&
!item.includes('.DS_Store') &&
// Exclude Rust compilation files
!/next-swc[\\/]target/.test(item)
!/packages[\\/]next-swc/.test(item)
)
},
}
......@@ -88,44 +88,29 @@ async function createNextInstall({
)
}
await rootSpan
.traceChild('ensure swc binary')
.traceAsyncFn(async () => {
// ensure swc binary is present in the native folder if
// not already built
for (const folder of await fs.readdir(
path.join(origRepoDir, 'node_modules/@next')
)) {
if (folder.startsWith('swc-')) {
const swcPkgPath = path.join(
origRepoDir,
'node_modules/@next',
folder
)
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))
))
)
},
})
}
}
})
const nativePath = path.join(origRepoDir, 'packages/next-swc/native')
pkgPaths = await rootSpan.traceChild('linkPackages').traceAsyncFn(() =>
linkPackages({
repoDir: tmpRepoDir,
})
)
const hasNativeBinary = fs
.readdirSync(nativePath)
.some((item) => item.endsWith('.node'))
if (hasNativeBinary) {
process.env.NEXT_TEST_NATIVE_DIR = nativePath
} else {
const swcDirectory = fs
.readdirSync(path.join(origRepoDir, 'node_modules/@next'))
.find((directory) => directory.startsWith('swc-'))
process.env.NEXT_TEST_NATIVE_DIR = swcDirectory
}
pkgPaths = await rootSpan
.traceChild('linkPackages')
.traceAsyncFn((span) =>
linkPackages({
repoDir: tmpRepoDir,
parentSpan: span,
})
)
}
const combinedDependencies = {
next: pkgPaths.get('next'),
......@@ -170,7 +155,7 @@ async function createNextInstall({
})
} else {
await rootSpan
.traceChild('run generic install command')
.traceChild('run generic install command', combinedDependencies)
.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