Unverified Commit 13292126 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[ci] Cleanup orphaned `next-stats-action` (#98348)

Became orphaned in https://github.com/vercel/next.js/pull/97792. Another
script and the test harness needed some utils from `next-stats-action`
so I moved that into `test/lib/link-packed-packages`.
parent 76a0bdbd
# syntax=docker.io/docker/dockerfile:1
# buildpack-deps already includes curl, ca-certificates, and git, so we avoid
# apt-get entirely (the arm64 apt mirror, ports.ubuntu.com, is unreliable).
FROM buildpack-deps:noble-scm AS base
RUN curl -sfLS https://install-node.vercel.app/v20.9.0 | bash -s -- -f
RUN npm i -g corepack@0.34.6
RUN corepack enable
FROM base AS pnpm-deploy
WORKDIR /dot-github
COPY --exclude=node_modules --exclude=actions/*/node_modules . .
RUN ls -l
RUN pnpm deploy --filter=next-stats-action --production /next-stats
FROM base AS next-stats-action
LABEL com.github.actions.name="Next.js PR Stats"
LABEL com.github.actions.description="Compares stats of a PR with the main branch"
LABEL repository="https://github.com/vercel/next.js"
RUN git config --global user.email 'stats@localhost' && \
git config --global user.name 'next stats'
WORKDIR /next-stats
COPY --from=pnpm-deploy /next-stats .
RUN pnpm install --production
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
# Next.js Stats GitHub Action
> Downloads and runs project with provided configs gathering stats to compare branches
See it in action at Next.js https://github.com/vercel/next.js
## Getting Started
1. Add a `.stats-app` folder to your project with a [`stats-config.js`](#stats-config) and any files to run against for example a test app that is to be built
2. Add the action to your [workflow](https://help.github.com/en/articles/configuring-a-workflow)
3. Enjoy the stats
## Stats Config
```TypeScript
const StatsConfig = {
// the Heading to show at the top of stats comments
commentHeading: 'Stats from current PR' | undefined,
commentReleaseHeading: 'Stats from current release' | undefined,
// the command to build your project if not done on post install
initialBuildCommand: undefined | string,
skipInitialInstall: undefined | boolean,
// the command to build the app (app source should be in `.stats-app`)
appBuildCommand: string,
appStartCommand: string | undefined,
// the main branch to compare against (what PRs will be merging into)
mainBranch: 'canary',
// the main repository path (relative to https://github.com/)
mainRepo: 'vercel/next.js',
// whether to attempt auto merging the main branch into PR before running stats
autoMergeMain: boolean | undefined,
// an array of configs for each run
configs: [
{ // first run's config
// title of the run
title: 'fastMode stats',
// whether to diff the outputted files (default: onOutputChange)
diff: 'onOutputChange' | false | undefined,
// config files to add before running diff (if `undefined` uses `configFiles`)
diffConfigFiles: [] | undefined,
// renames to apply to make file names deterministic
renames: [
{
srcGlob: 'main-*.js',
dest: 'main.js'
}
],
// config files to add before running (removed before successive runs)
configFiles: [
{
path: './next.config.js',
content: 'module.exports = { fastMode: true }'
}
],
// an array of file groups to diff/track
filesToTrack: [
{
name: 'Pages',
globs: [
'build/pages/**/*.js'
]
}
],
// an array of URLs to fetch while `appStartCommand` is running
// will be output to fetched-pages/${pathname}.html
pagesToFetch: [
'https://localhost:$PORT/page-1'
]
},
{ // second run's config
title: 'slowMode stats',
diff: false,
configFiles: [
{
path: './next.config.js',
content: 'module.exports = { slowMode: true }'
}
],
filesToTrack: [
{
name: 'Main Bundles',
globs: [
'build/runtime/webpack-*.js',
'build/runtime/main-*.js',
]
}
]
},
]
}
module.exports = StatsConfig
```
name: 'Next.js PR Stats'
description: 'Compare PR stats with canary'
inputs:
bundler:
description: 'Bundler to benchmark (webpack|turbopack|both)'
default: 'both'
required: false
runs:
using: 'docker'
# this dockerfile must be located in the parent directory, otherwise
# `pnpm deploy` can't read the pnpm-lock.yaml
image: '../../next-stats-action.Dockerfile'
#!/usr/bin/env bash
set -eu # stop on error
export HOME=/root
node /next-stats/src/index.js
# Ignore everything in this directory
*
# Except this file
!.gitignore
\ No newline at end of file
{
"name": "next-stats-action",
"private": true,
"main": "src/index.js",
"dependencies": {
"@vercel/kv": "^1.0.1",
"async-sema": "^3.1.0",
"execa": "2.0.3",
"get-port": "^5.0.0",
"glob": "^7.1.4",
"gzip-size": "^5.1.1",
"minimatch": "^3.0.4",
"node-fetch": "^2.6.0",
"prettier": "^2.8.4",
"pretty-bytes": "^5.3.0",
"pretty-ms": "^5.0.0",
"semver": "7.3.4"
},
"devDependencies": {
"typescript": "5.1.6"
},
"engines": {
"node": ">=20.9.0"
},
"packageManager": "pnpm@10.33.0"
}
This diff is collapsed.
#!/usr/bin/env node
/**
* Aggregates results from sharded stats runs and posts combined comment
*
* Usage: node aggregate-results.js <results-dir>
*
* Expects JSON files named pr-stats-*.json in the results directory
*/
const path = require('path')
const fs = require('fs/promises')
const { existsSync } = require('fs')
const addComment = require('./add-comment')
const logger = require('./util/logger')
const BUNDLER_DISPLAY_NAMES = {
webpack: 'Webpack',
turbopack: 'Turbopack',
}
function getBundlerDisplayName(bundler) {
return (
BUNDLER_DISPLAY_NAMES[bundler] ||
bundler.charAt(0).toUpperCase() + bundler.slice(1)
)
}
// The bundlers the `stats` matrix is expected to produce results for, provided
// by the workflow via STATS_EXPECTED_BUNDLERS. A bundler whose job failed, was
// cancelled, or timed out never uploads its pr-stats-<bundler>.json artifact, so
// comparing the expected set against the artifacts present tells us which
// bundlers are missing. Returns an empty list when unset (e.g. local runs), in
// which case we don't attempt to report missing bundlers.
function getExpectedBundlers() {
const raw = process.env.STATS_EXPECTED_BUNDLERS
if (!raw) return []
return raw
.split(/[\s,]+/)
.map((b) => b.trim().toLowerCase())
.filter(Boolean)
}
// Extract the bundler slug from a `pr-stats-<bundler>.json` filename.
function getBundlerFromStatsFile(file) {
const match = file.match(/^pr-stats-(.+)\.json$/)
return match ? match[1].toLowerCase() : null
}
async function main() {
const resultsDir = process.argv[2] || process.cwd()
logger(`Aggregating results from: ${resultsDir}`)
// Find all pr-stats-*.json files
const files = await fs.readdir(resultsDir)
const statsFiles = files.filter(
(f) => f.startsWith('pr-stats-') && f.endsWith('.json')
)
// Work out which bundlers are missing so we can report them in the comment.
const expectedBundlers = getExpectedBundlers()
const presentBundlers = statsFiles
.map(getBundlerFromStatsFile)
.filter(Boolean)
const missingBundlers = expectedBundlers.filter(
(bundler) => !presentBundlers.includes(bundler)
)
if (missingBundlers.length > 0) {
logger(
`Missing stats for bundler(s): ${missingBundlers.join(', ')} ` +
`(their job failed, was cancelled, or timed out)`
)
}
if (statsFiles.length === 0) {
// The aggregate step only runs for non-docs changes (docs-only changes skip
// it via the DOCS_CHANGE gate), so the absence of any artifact means no
// bundler produced results. Only surface an "all bundlers failed" notice
// when the stats jobs genuinely failed. A 'cancelled' result here means the
// whole run was cancelled (superseded, or every bundler cancelled); we stay
// silent so scripts/pr-ci-comment.mjs posts the cancelled notice instead of
// a misleading failure comment for a run that never really ran.
const statsResult = process.env.STATS_RESULT
if (expectedBundlers.length === 0 || statsResult !== 'failure') {
logger(
`No pr-stats-*.json files found (stats result: ${statsResult || 'unknown'}) - nothing to aggregate`
)
process.exit(0)
}
logger(
`No pr-stats-*.json files found - all bundler jobs ` +
`(${expectedBundlers.join(', ')}) failed`
)
// No successful run means we don't have the actionInfo/statsConfig captured
// inside a pr-stats file, so synthesize the minimum addComment needs to
// render the "all bundlers failed" notice. In CI the rendered comment is
// read from this job's logs and posted by scripts/pr-ci-comment.mjs; the
// direct-post path in addComment is a no-op without a token/endpoint.
await addComment(
[],
{ isRelease: false, commitId: null },
{},
{ missingBundlers: expectedBundlers.map(getBundlerDisplayName) }
)
process.exit(0)
}
logger(`Found ${statsFiles.length} results files: ${statsFiles.join(', ')}`)
// Load all results
const allData = []
for (const file of statsFiles) {
const filePath = path.join(resultsDir, file)
try {
const content = await fs.readFile(filePath, 'utf8')
const data = JSON.parse(content)
allData.push(data)
logger(`Loaded ${file} successfully`)
} catch (err) {
logger(`Warning: Failed to load ${file}: ${err.message}`)
}
}
if (allData.length === 0) {
logger('No valid results files could be loaded')
process.exit(1)
}
// Use the first file's actionInfo and statsConfig
const { actionInfo, statsConfig } = allData[0]
// Re-inject the GitHub token from env (it's excluded from JSON serialization for security)
actionInfo.githubToken = process.env.PR_STATS_COMMENT_TOKEN
// Merge results from all files
// Each file has results array with {title, mainRepoStats, diffRepoStats, diffs}
// We need to merge stats objects by combining their keys
const mergedResults = []
// Assume all files have the same number of configs with same titles
const numConfigs = allData[0].results.length
for (let i = 0; i < numConfigs; i++) {
const title = allData[0].results[i].title
const mergedMainRepoStats = {}
const mergedDiffRepoStats = {}
let mergedDiffs = null
for (const data of allData) {
const result = data.results[i]
// Merge mainRepoStats
if (result.mainRepoStats) {
for (const [key, value] of Object.entries(result.mainRepoStats)) {
if (!mergedMainRepoStats[key]) {
mergedMainRepoStats[key] = {}
}
Object.assign(mergedMainRepoStats[key], value)
}
}
// Merge diffRepoStats
if (result.diffRepoStats) {
for (const [key, value] of Object.entries(result.diffRepoStats)) {
if (!mergedDiffRepoStats[key]) {
mergedDiffRepoStats[key] = {}
}
Object.assign(mergedDiffRepoStats[key], value)
}
}
// Merge diffs (just combine all diff objects)
if (result.diffs) {
if (!mergedDiffs) {
mergedDiffs = {}
}
Object.assign(mergedDiffs, result.diffs)
}
}
mergedResults.push({
title,
mainRepoStats: mergedMainRepoStats,
diffRepoStats: mergedDiffRepoStats,
diffs: mergedDiffs,
})
}
logger(
`Merged ${allData.length} result sets into ${mergedResults.length} configs`
)
// Post the combined comment
await addComment(mergedResults, actionInfo, statsConfig, {
missingBundlers: missingBundlers.map(getBundlerDisplayName),
})
logger('Aggregation complete')
}
main().catch((err) => {
console.error('Error aggregating results:', err)
process.exit(1)
})
const path = require('path')
const os = require('os')
const fs = require('fs')
const benchTitle = 'Page Load Tests'
function getTempRoot() {
const tempRoot = process.env.RUNNER_TEMP || os.tmpdir()
try {
fs.mkdirSync(tempRoot, { recursive: true })
return tempRoot
} catch {
return os.tmpdir()
}
}
const workDir = fs.mkdtempSync(path.join(getTempRoot(), 'next-stats-'))
const pnpmStoreDir = path.join(workDir, '.pnpm-store')
const mainRepoDir = path.join(workDir, 'main-repo')
const diffRepoDir = path.join(workDir, 'diff-repo')
const statsAppDir = path.join(workDir, 'stats-app')
const diffingDir = path.join(workDir, 'diff')
const allowedConfigLocations = [
'./',
'.stats-app',
'test/.stats-app',
'.github/.stats-app',
]
module.exports = {
benchTitle,
workDir,
pnpmStoreDir,
diffingDir,
mainRepoDir,
diffRepoDir,
statsAppDir,
allowedConfigLocations,
}
const path = require('path')
const fs = require('fs/promises')
const { existsSync } = require('fs')
const exec = require('./util/exec')
const logger = require('./util/logger')
const runConfigs = require('./run')
const addComment = require('./add-comment')
const actionInfo = require('./prepare/action-info')()
const { mainRepoDir, diffRepoDir, pnpmStoreDir } = require('./constants')
const loadStatsConfig = require('./prepare/load-stats-config')
const { cloneRepo, mergeBranch, getCommitId, linkPackages, getLastStable } =
require('./prepare/repo-setup')(actionInfo)
const allowedActions = new Set(['synchronize', 'opened'])
// Get bundler filter from action input (set by GitHub Actions as INPUT_BUNDLER)
const bundlerInput = (process.env.INPUT_BUNDLER || 'both').toLowerCase()
const isShardedRun = bundlerInput !== 'both'
if (isShardedRun) {
logger(`Running in sharded mode for bundler: ${bundlerInput}`)
}
if (!allowedActions.has(actionInfo.actionName) && !actionInfo.isRelease) {
logger(
`Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}`
)
process.exit(0)
}
;(async () => {
try {
if (existsSync(path.join(__dirname, '../SKIP_NEXT_STATS.txt'))) {
console.log(
'SKIP_NEXT_STATS.txt file present, exiting stats generation..'
)
process.exit(0)
}
const { stdout: gitName } = await exec(
'git config user.name && git config user.email'
)
console.log('git author result:', gitName)
// clone PR/newer repository/ref first to get settings
if (!actionInfo.skipClone) {
await cloneRepo(actionInfo.prRepo, diffRepoDir, actionInfo.prRef)
}
if (actionInfo.isRelease) {
process.env.STATS_IS_RELEASE = 'true'
}
// load stats config from allowed locations
const { statsConfig, relativeStatsAppDir } = loadStatsConfig()
if (actionInfo.isLocal && actionInfo.prRef === statsConfig.mainBranch) {
throw new Error(
`'GITHUB_REF' can not be the same as mainBranch in 'stats-config.js'.\n` +
`This will result in comparing against the same branch`
)
}
if (actionInfo.isLocal) {
// make sure to use local repo location instead of the
// one provided in statsConfig
statsConfig.mainRepo = actionInfo.prRepo
}
/* eslint-disable-next-line */
actionInfo.commitId = await getCommitId(diffRepoDir)
if (!actionInfo.skipClone) {
let mainRef = statsConfig.mainBranch
if (actionInfo.isRelease) {
logger(`Release detected, using last stable tag: "${actionInfo.prRef}"`)
const lastStableTag = await getLastStable(diffRepoDir, actionInfo.prRef)
mainRef = lastStableTag
if (!lastStableTag) throw new Error('failed to get last stable tag')
logger(`using latestStable: "${lastStableTag}"`)
/* eslint-disable-next-line */
actionInfo.lastStableTag = lastStableTag
/* eslint-disable-next-line */
actionInfo.commitId = await getCommitId(diffRepoDir)
if (!actionInfo.customCommentEndpoint) {
/* eslint-disable-next-line */
actionInfo.commentEndpoint = `https://api.github.com/repos/${statsConfig.mainRepo}/commits/${actionInfo.commitId}/comments`
}
}
await cloneRepo(statsConfig.mainRepo, mainRepoDir, mainRef)
if (!actionInfo.isRelease && statsConfig.autoMergeMain) {
logger('Attempting auto merge of main branch')
await mergeBranch(statsConfig.mainBranch, mainRepoDir, diffRepoDir)
}
}
let mainRepoPkgPaths
let diffRepoPkgPaths
// run install/initialBuildCommand
const repoDirs = [mainRepoDir, diffRepoDir]
for (const dir of repoDirs) {
logger(`Running initial build for ${dir}`)
if (!actionInfo.skipClone) {
// TODO: we can remove this `packageManager` modification once Next.js
// 16.3 is released, but we must override it for now because 16.2 uses
// pnpm 9.6.0, which supports different arguments. `diffRepoDir`
// points to the most recent stable tag.
const packageJson = path.join(dir, 'package.json')
const packageJsonContents = JSON.parse(
await fs.readFile(packageJson, { encoding: 'utf8' })
)
packageJsonContents.packageManager = 'pnpm@10.33.0'
if (packageJsonContents.engines != null) {
delete packageJsonContents.engines.pnpm
}
await fs.writeFile(
packageJson,
JSON.stringify(packageJsonContents, null, ' ')
)
if (!statsConfig.skipInitialInstall) {
const command =
'pnpm install ' +
// tolerate lockfile changes from merging latest changes
'--no-frozen-lockfile ' +
// colocate the store with the workdir to avoid EXDEV hardlink or
// reflink failures across the container's bind-mounted workdir and
// overlayfs root.
`--store-dir=${pnpmStoreDir}`
await exec.spawnPromise(command, {
env: { PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1' },
cwd: dir,
})
await exec.spawnPromise(
statsConfig.initialBuildCommand || 'pnpm build',
{ cwd: dir }
)
}
}
const nativeDir = path.join(dir, 'packages/next-swc/native')
await fs
.cp(path.join(__dirname, '../native'), nativeDir, {
recursive: true,
force: true,
})
.catch(console.error)
process.env.NEXT_TEST_NATIVE_DIR = nativeDir
logger(`Packing packages in ${dir}`)
const turboJsonPath = path.join(dir, 'turbo.json')
let hasTurboPackTask = false
try {
const turboJson = JSON.parse(
await fs.readFile(turboJsonPath, { encoding: 'utf8' })
)
hasTurboPackTask =
turboJson.tasks?.['pack-for-isolated-tests'] !== undefined
} catch {}
if (hasTurboPackTask) {
await exec.spawnPromise('pnpm turbo run pack-for-isolated-tests', {
cwd: dir,
})
} else {
// Temporary fallback because stats action run on the canary branch which does not have the pack-for-isolated-tests task yet.
logger(
'turbo task pack-for-isolated-tests not found, falling back to pnpm pack per package'
)
const packagesDir = path.join(dir, 'packages')
const packageFolders = await fs.readdir(packagesDir)
await Promise.all(
packageFolders.map(async (folder) => {
const pkgDir = path.join(packagesDir, folder)
const pkgJsonPath = path.join(pkgDir, 'package.json')
if (!existsSync(pkgJsonPath)) return
try {
await exec.spawnPromise('pnpm pack --out packed.tgz', {
cwd: pkgDir,
})
} catch (err) {
logger(`Failed to pack ${folder}: ${err.message}`)
}
})
)
}
logger(`Linking packages in ${dir}`)
const pkgPaths = await linkPackages({
repoDir: dir,
})
if (dir === mainRepoDir) mainRepoPkgPaths = pkgPaths
else diffRepoPkgPaths = pkgPaths
}
// run the configs and collect results
const results = await runConfigs(statsConfig.configs, {
statsConfig,
mainRepoPkgPaths,
diffRepoPkgPaths,
relativeStatsAppDir,
bundlerFilter: isShardedRun ? bundlerInput : null,
})
if (isShardedRun) {
// In sharded mode, save results to JSON for later aggregation
const resultsPath = path.join(
process.env.GITHUB_WORKSPACE || process.cwd(),
`pr-stats-${bundlerInput}.json`
)
// Exclude sensitive fields (githubToken) before serializing to JSON
const { githubToken, ...safeActionInfo } = actionInfo
await fs.writeFile(
resultsPath,
JSON.stringify(
{ results, actionInfo: safeActionInfo, statsConfig },
null,
2
)
)
logger(`Saved results to ${resultsPath}`)
} else {
// In non-sharded mode, post comment directly
await addComment(results, actionInfo, statsConfig)
}
logger('finished')
process.exit(0)
} catch (err) {
console.error('Error occurred generating stats:')
console.error(err)
process.exit(1)
}
})()
const path = require('path')
const logger = require('../util/logger')
const { execSync } = require('child_process')
const releaseTypes = new Set(['release', 'published'])
module.exports = function actionInfo() {
let {
ISSUE_ID,
SKIP_CLONE,
GITHUB_REF,
LOCAL_STATS,
GIT_ROOT_DIR,
GITHUB_ACTION,
COMMENT_ENDPOINT,
GITHUB_REPOSITORY,
GITHUB_EVENT_PATH,
PR_STATS_COMMENT_TOKEN,
PREVIEW_BUILDS_BASE_URL,
} = process.env
delete process.env.GITHUB_TOKEN
delete process.env.PR_STATS_COMMENT_TOKEN
// only use custom endpoint if we don't have a token
const commentEndpoint = !PR_STATS_COMMENT_TOKEN && COMMENT_ENDPOINT
if (LOCAL_STATS === 'true') {
const cwd = process.cwd()
const parentDir = path.join(cwd, '../..')
if (!GITHUB_REF) {
// get the current branch name
GITHUB_REF = execSync(`cd "${cwd}" && git rev-parse --abbrev-ref HEAD`)
.toString()
.trim()
}
if (!GIT_ROOT_DIR) {
GIT_ROOT_DIR = path.join(parentDir, '/')
}
if (!GITHUB_REPOSITORY) {
GITHUB_REPOSITORY = path.relative(parentDir, cwd)
}
if (!GITHUB_ACTION) {
GITHUB_ACTION = 'opened'
}
}
const info = {
commentEndpoint,
skipClone: SKIP_CLONE,
actionName: GITHUB_ACTION,
githubToken: PR_STATS_COMMENT_TOKEN,
customCommentEndpoint: !!commentEndpoint,
gitRoot: GIT_ROOT_DIR || 'https://github.com/',
prRepo: GITHUB_REPOSITORY,
prRef: GITHUB_REF,
isLocal: LOCAL_STATS,
commitId: null,
issueId: ISSUE_ID,
isRelease:
GITHUB_REPOSITORY === 'vercel/next.js' &&
(GITHUB_REF || '').includes('canary'),
previewBuildsBaseUrl:
PREVIEW_BUILDS_BASE_URL || 'https://vercel-packages.vercel.app/next',
}
if (info.isRelease) {
info.prRef = 'canary'
}
// get comment
if (GITHUB_EVENT_PATH) {
const event = require(GITHUB_EVENT_PATH)
info.actionName = event.action || info.actionName
if (releaseTypes.has(info.actionName)) {
info.isRelease = true
} else {
// since GITHUB_REPOSITORY and REF might not match the fork
// use event data to get repository and ref info
const prData = event['pull_request']
if (prData) {
info.prRepo = prData.head.repo.full_name
info.prRef = prData.head.ref
info.issueId = prData.number
if (!info.commentEndpoint) {
info.commentEndpoint = prData._links.comments || ''
}
// comment endpoint might be under `href`
if (typeof info.commentEndpoint === 'object') {
info.commentEndpoint = info.commentEndpoint.href
}
}
}
}
logger('Got actionInfo:')
logger.json({
...info,
githubToken: PR_STATS_COMMENT_TOKEN ? 'found' : 'missing',
})
return info
}
const path = require('path')
const logger = require('../util/logger')
const { diffRepoDir, allowedConfigLocations } = require('../constants')
// load stats-config
function loadStatsConfig() {
let statsConfig
let relativeStatsAppDir
for (const configPath of allowedConfigLocations) {
try {
relativeStatsAppDir = configPath
statsConfig = require(
path.join(diffRepoDir, configPath, 'stats-config.js')
)
break
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
console.error('Failed to load stats-config at', configPath, err)
}
/* */
}
}
if (!statsConfig) {
throw new Error(
`Failed to locate \`.stats-app\`, allowed locations are: ${allowedConfigLocations.join(
', '
)}`
)
}
logger(
'Got statsConfig at',
path.join(relativeStatsAppDir, 'stats-config.js'),
statsConfig,
'\n'
)
return { statsConfig, relativeStatsAppDir }
}
module.exports = loadStatsConfig
const path = require('path')
const fs = require('fs')
const { existsSync } = require('fs')
const exec = require('../util/exec')
const logger = require('../util/logger')
module.exports = (actionInfo) => {
return {
async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') {
await fs.promises.rm(dest, { recursive: true, force: true })
await exec(
`git clone ${actionInfo.gitRoot}${repoPath} --single-branch --branch ${branch} --depth=${depth} ${dest}`
)
},
async getLastStable() {
const res = await fetch(
`https://api.github.com/repos/vercel/next.js/releases/latest`,
{
headers: {
'X-GitHub-Api-Version': '2022-11-28',
},
}
)
if (!res.ok) {
throw new Error(
`Failed to get latest stable tag ${res.status}: ${await res.text()}`
)
}
const data = await res.json()
return data.tag_name
},
async getCommitId(repoDir = '') {
const { stdout } = await exec(`cd ${repoDir} && git rev-parse HEAD`)
return stdout.trim()
},
async resetToRef(ref = '', repoDir = '') {
await exec(`cd ${repoDir} && git reset --hard ${ref}`)
},
async mergeBranch(ref = '', origRepoDir = '', destRepoDir = '') {
await exec(`cd ${destRepoDir} && git remote add upstream ${origRepoDir}`)
await exec(`cd ${destRepoDir} && git fetch upstream`)
try {
await exec(`cd ${destRepoDir} && git merge upstream/${ref}`)
logger('Auto merge of main branch successful')
} catch (err) {
logger.error('Failed to auto merge main branch:', err)
if (err.stdout && err.stdout.includes('CONFLICT')) {
await exec(`cd ${destRepoDir} && git merge --abort`)
logger('aborted auto merge')
}
}
},
/**
* Scans pre-built `packed.tgz` tarballs produced by `turbo run pack`
* in each package under `repoDir/packages/`.
* @param {{ repoDir: string }} options
* @returns {Promise<Map<string, string>>} Map of package name to tarball path
*/
async linkPackages({ repoDir }) {
/** @type {Map<string, string>} */
const pkgPaths = new Map()
let packageFolders
try {
packageFolders = await fs.promises.readdir(
path.join(repoDir, 'packages')
)
} catch (err) {
if (err.code === 'ENOENT') {
require('console').log('no packages to link')
return pkgPaths
}
throw err
}
for (const packageFolder of packageFolders) {
const packagePath = path.join(repoDir, 'packages', packageFolder)
const tarballPath = path.join(packagePath, 'packed.tgz')
const packageJsonPath = path.join(packagePath, 'package.json')
if (!existsSync(packageJsonPath) || !existsSync(tarballPath)) {
continue
}
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
pkgPaths.set(packageJson.name, tarballPath)
}
require('console').log(
`Found ${pkgPaths.size} packed tarballs:`,
Array.from(pkgPaths.keys()).join(', ')
)
return pkgPaths
},
}
}
const exec = require('../util/exec')
const parseField = (stdout = '', field = '') => {
return stdout.split(field).pop().trim().split(/\s/).shift().trim()
}
// benchmark an url
async function benchmarkUrl(
url = '',
options = {
reqTimeout: 60,
concurrency: 50,
numRequests: 2500,
}
) {
const { numRequests, concurrency, reqTimeout } = options
const { stdout } = await exec(
`ab -n ${numRequests} -c ${concurrency} -s ${reqTimeout} "${url}"`
)
const totalTime = parseFloat(parseField(stdout, 'Time taken for tests:'), 10)
const failedRequests = parseInt(parseField(stdout, 'Failed requests:'), 10)
const avgReqPerSec = parseFloat(parseField(stdout, 'Requests per second:'))
return {
totalTime,
avgReqPerSec,
failedRequests,
}
}
module.exports = benchmarkUrl
const path = require('path')
const fs = require('fs/promises')
const { existsSync } = require('fs')
const exec = require('../util/exec')
const glob = require('../util/glob')
const logger = require('../util/logger')
const { statsAppDir, diffingDir } = require('../constants')
module.exports = async function collectDiffs(
filesToTrack = [],
initial = false
) {
if (initial) {
logger('Setting up directory for diffing')
// set-up diffing directory
await fs.rm(diffingDir, { recursive: true, force: true })
await fs.mkdir(diffingDir, { recursive: true })
await exec(`cd ${diffingDir} && git init`)
} else {
// remove any previous files in case they won't be overwritten
const toRemove = await glob('!(.git)', { cwd: diffingDir, dot: true })
await Promise.all(
toRemove.map((file) =>
fs.rm(path.join(diffingDir, file), { recursive: true, force: true })
)
)
}
const diffs = {}
await Promise.all(
filesToTrack.map(async (fileGroup) => {
const { globs } = fileGroup
const curFiles = []
const prettierExts = ['.js', '.html', '.css', '.json']
await Promise.all(
globs.map(async (pattern) => {
curFiles.push(
...(await glob(pattern, { cwd: statsAppDir })).filter((item) =>
prettierExts.includes(path.extname(item))
)
)
})
)
logger('Tracking the following files:')
logger(curFiles)
for (let file of curFiles) {
const absPath = path.join(statsAppDir, file)
const diffDest = path.join(diffingDir, file)
await fs.cp(absPath, diffDest, { recursive: true, force: true })
}
if (curFiles.length > 0) {
const prettierPath = path.join(
__dirname,
'../../node_modules/.bin/prettier'
)
await exec(
`cd "${process.env.LOCAL_STATS ? process.cwd() : diffingDir}" && ` +
`${prettierPath} --write --no-error-on-unmatched-pattern ${curFiles
.map((f) => path.join(diffingDir, f))
.join(' ')}`
)
}
})
)
await exec(`cd ${diffingDir} && git add .`, true)
if (initial) {
await exec(`cd ${diffingDir} && git commit -m 'initial commit'`)
} else {
let { stdout: renamedFiles } = await exec(
`cd ${diffingDir} && git diff --name-status HEAD`
)
renamedFiles = renamedFiles
.trim()
.split('\n')
.filter((line) => line.startsWith('R'))
diffs._renames = []
for (const line of renamedFiles) {
const [, prev, cur] = line.split('\t')
await fs.rename(path.join(diffingDir, cur), path.join(diffingDir, prev))
diffs._renames.push({
prev,
cur,
})
}
await exec(`cd ${diffingDir} && git add .`)
let { stdout: changedFiles } = await exec(
`cd ${diffingDir} && git diff --name-only HEAD`
)
changedFiles = changedFiles.trim().split('\n')
for (const file of changedFiles) {
const fileKey = path.basename(file)
const hasFile = existsSync(path.join(diffingDir, file))
if (!hasFile) {
diffs[fileKey] = 'deleted'
continue
}
try {
let { stdout } = await exec(
`cd ${diffingDir} && git diff --minimal HEAD ${file}`
)
stdout = (stdout.split(file).pop() || '').trim()
if (stdout.length > 0 && !isLikelyHashOrIDChange(stdout)) {
diffs[fileKey] = stdout
}
} catch (err) {
console.error(`Failed to diff ${file}: ${err.message}`)
diffs[fileKey] = `failed to diff`
}
}
}
return diffs
}
function isLikelyHashOrIDChange(diff) {
const lines = diff.split('\n')
let additions = []
let deletions = []
// Separate additions and deletions
for (const line of lines) {
if (line.startsWith('+')) {
additions.push(line.substring(1).split(/\b/))
} else if (line.startsWith('-')) {
deletions.push(line.substring(1).split(/\b/))
}
}
// If the number of additions and deletions is different, it's not a hash or ID change
if (additions.length !== deletions.length) {
return false
}
// Compare each addition with each deletion
for (let i = 0; i < additions.length; i++) {
const additionTokens = additions[i]
const deletionTokens = deletions[i]
// Identify differing tokens
const differingTokens = additionTokens.filter(
(token, index) => token !== deletionTokens[index]
)
// Analyze differing tokens
for (const token of differingTokens) {
const isLikelyHash = /^[a-f0-9]+$/.test(token)
const isLikelyID = /^[0-9]+$/.test(token)
// this is most likely noise because some path include the repo name, which can be main or diff
const isLikelyNoise = ['main', 'diff'].includes(token)
if (!isLikelyHash && !isLikelyID && !isLikelyNoise) {
return false
}
}
}
return true
}
const path = require('path')
const fs = require('fs/promises')
// getDirSize recursively gets size of all files in a directory
async function getDirSize(dir, ctx = { size: 0 }) {
let subDirs = await fs.readdir(dir)
subDirs = subDirs.map((d) => path.join(dir, d))
await Promise.all(
subDirs.map(async (curDir) => {
// we use dev builds so the size isn't helpful to track
// here as it's not reflective of full releases
if (curDir.includes('@next/swc')) return
const fileStat = await fs.stat(curDir)
if (fileStat.isDirectory()) {
return getDirSize(curDir, ctx)
}
ctx.size += fileStat.size
})
)
return ctx.size
}
module.exports = getDirSize
This diff is collapsed.
const logger = require('./logger')
const { promisify } = require('util')
const { exec: execOrig, spawn: spawnOrig } = require('child_process')
const execP = promisify(execOrig)
const env = {
...process.env,
GITHUB_TOKEN: '',
PR_STATS_COMMENT_TOKEN: '',
}
function exec(command, noLog = false, opts = {}) {
if (!noLog) logger(`exec: ${command}`)
return execP(command, {
...opts,
env: { ...env, ...opts.env },
})
}
exec.spawn = function spawn(command = '', opts = {}) {
logger(`spawn: ${command}`)
const child = spawnOrig('/bin/bash', ['-c', command], {
...opts,
env: {
...env,
...opts.env,
},
stdio: opts.stdio || 'inherit',
})
child.on('exit', (code, signal) => {
logger(`spawn exit (${code}, ${signal}): ${command}`)
})
return child
}
exec.spawnPromise = function spawnPromise(command = '', opts = {}) {
return new Promise((resolve, reject) => {
const child = exec.spawn(command, opts)
child.on('exit', (code, signal) => {
if (code || signal) {
return reject(
new Error(`bad exit code/signal code: ${code} signal: ${signal}`)
)
}
resolve()
})
})
}
module.exports = exec
const globOrig = require('glob')
const { promisify } = require('util')
module.exports = promisify(globOrig)
function logger(...args) {
console.log(...args)
}
logger.json = (obj) => {
logger('\n', JSON.stringify(obj, null, 2), '\n')
}
logger.error = (...args) => {
console.error(...args)
}
logger.warn = (...args) => {
console.warn(...args)
}
module.exports = logger
/**
* Shared statistics utilities for benchmark measurements
*/
/**
* Calculate statistical summary for an array of numbers
* @param {number[]} arr - Array of numeric values
* @returns {Object|null} Stats object with median, min, max, mean, stddev, cv or null if empty
*/
function calcStats(arr) {
if (arr.length === 0) return null
const sorted = [...arr].sort((a, b) => a - b)
const mid = Math.floor(sorted.length / 2)
const median =
sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
const min = sorted[0]
const max = sorted[sorted.length - 1]
const mean = arr.reduce((a, b) => a + b, 0) / arr.length
const variance =
arr.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / arr.length
const stddev = Math.sqrt(variance)
const cv = mean > 0 ? (stddev / mean) * 100 : 0 // coefficient of variation as %
return {
median,
min,
max,
mean: Math.round(mean),
stddev: Math.round(stddev),
cv: Math.round(cv),
}
}
module.exports = { calcStats }
#!/usr/bin/env node
/**
* Test the stats action comment formatting locally
*
* Usage: node test-local.js [--with-history]
*
* This generates a sample PR comment using mock data so you can
* quickly verify formatting changes without running the full action.
*
* Options:
* --with-history Simulate KV history data to test trend sparklines
*/
const addComment = require('./src/add-comment')
const withHistory = process.argv.includes('--with-history')
// Mock data simulating real benchmark results
const mockResults = [
{
title: 'Default Build',
mainRepoStats: {
General: {
nextDevColdListenDurationTurbo: 280,
nextDevColdReadyDurationTurbo: 450,
nextDevWarmListenDurationTurbo: 180,
nextDevWarmReadyDurationTurbo: 320,
nextDevColdListenDurationWebpack: 350,
nextDevColdReadyDurationWebpack: 1200,
nextDevWarmListenDurationWebpack: 250,
nextDevWarmReadyDurationWebpack: 800,
nextStartReadyDuration: 150,
buildDurationTurbo: 4500,
buildDurationCachedTurbo: 4200,
buildDurationWebpack: 14000,
buildDurationCachedWebpack: 13500,
nodeModulesSize: 250000000,
},
},
diffRepoStats: {
General: {
nextDevColdListenDurationTurbo: 290, // +10ms (insignificant)
nextDevColdReadyDurationTurbo: 520, // +70ms at 15% (significant regression)
nextDevWarmListenDurationTurbo: 175, // -5ms (insignificant)
nextDevWarmReadyDurationTurbo: 280, // -40ms at 12% (significant improvement)
nextDevColdListenDurationWebpack: 360,
nextDevColdReadyDurationWebpack: 1180,
nextDevWarmListenDurationWebpack: 245,
nextDevWarmReadyDurationWebpack: 790,
nextStartReadyDuration: 145,
buildDurationTurbo: 4400,
buildDurationCachedTurbo: 4250,
buildDurationWebpack: 13800,
buildDurationCachedWebpack: 13600,
nodeModulesSize: 251000000,
},
},
diffs: null,
},
]
const mockActionInfo = {
isRelease: false,
commitId: 'abc123',
issueId: 12345,
}
const mockStatsConfig = {
commentHeading: 'Stats from current PR',
}
// Run with LOCAL_STATS to output to file instead of posting
process.env.LOCAL_STATS = 'true'
// Mock the KV module to provide fake history if --with-history is passed
if (withHistory) {
// Generate mock history entries showing a trend
const mockHistory = []
for (let i = 0; i < 10; i++) {
mockHistory.push({
commitId: `commit-${i}`,
timestamp: new Date(Date.now() - i * 86400000).toISOString(),
metrics: {
nextDevColdReadyDurationTurbo: 400 + Math.random() * 100, // varies 400-500
nextDevWarmReadyDurationTurbo: 300 + Math.random() * 50,
buildDurationTurbo: 4000 + Math.random() * 1000,
},
})
}
// Inject mock KV client
process.env.KV_REST_API_URL = 'mock://kv'
process.env.KV_REST_API_TOKEN = 'mock-token'
// Patch the require to intercept @vercel/kv
const Module = require('module')
const originalRequire = Module.prototype.require
Module.prototype.require = function (id) {
if (id === '@vercel/kv') {
return {
createClient: () => ({
lrange: async () => mockHistory,
rpush: async () => {},
ltrim: async () => {},
}),
}
}
return originalRequire.apply(this, arguments)
}
console.log('Running with mock history data (10 entries)')
}
addComment(mockResults, mockActionInfo, mockStatsConfig)
.then(() =>
console.log(
'\nGenerated pr-stats.md - open it to see the comment' +
(withHistory ? ' (with trend sparklines)' : '')
)
)
.catch(console.error)
# syntax=docker.io/docker/dockerfile:1
# buildpack-deps already includes curl, ca-certificates, and git, so we avoid
# apt-get entirely (the arm64 apt mirror, ports.ubuntu.com, is unreliable).
FROM buildpack-deps:noble-scm AS base
RUN curl -sfLS https://install-node.vercel.app/v20.9.0 | bash -s -- -f
RUN npm i -g corepack@0.34.6
RUN corepack enable
FROM base AS pnpm-deploy
WORKDIR /dot-github
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY --exclude=actions/*/node_modules \
actions/next-stats-action actions/next-stats-action
RUN pnpm deploy --filter=next-stats-action --production /next-stats
FROM base AS next-stats-action
LABEL com.github.actions.name="Next.js PR Stats"
LABEL com.github.actions.description="Compares stats of a PR with the main branch"
LABEL repository="https://github.com/vercel/next.js"
RUN git config --global user.email 'stats@localhost' && \
git config --global user.name 'next stats'
WORKDIR /next-stats
COPY --from=pnpm-deploy /next-stats .
COPY actions/next-stats-action/entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
This diff is collapsed.
......@@ -58,7 +58,6 @@
"test-turbo": "scripts/run-jest.sh --bundler=turbo --headless --",
"testonly": "jest --runInBand",
"testheadless": "scripts/run-jest.sh --headless --",
"genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js",
"git-reset": "git reset --hard HEAD",
"git-clean": "git clean -d -x -e node_modules -e packages -f",
"typescript": "tsc --noEmit",
......
#!/usr/bin/env bash
if [[ $(node ./scripts/check-is-release.js 2> /dev/null || :) == v* ]];
then
echo "Publish occurred, running release stats..."
else
echo "Not publish commit, exiting..."
touch .github/actions/next-stats-action/SKIP_NEXT_STATS.txt
exit 0;
fi
if [[ -z "$NPM_TOKEN" ]];then
echo "No NPM_TOKEN, exiting.."
exit 0;
fi
echo "Waiting 30 seconds to allow publish to finalize"
sleep 30
......@@ -5,8 +5,7 @@ const fsp = require('fs/promises')
const prettyBytes = require('pretty-bytes')
const gzipSize = require('next/dist/compiled/gzip-size')
const { nodeFileTrace } = require('next/dist/compiled/@vercel/nft')
const { linkPackages } =
require('../.github/actions/next-stats-action/src/prepare/repo-setup')()
const { linkPackages } = require('../test/lib/link-packed-packages')
const MAX_COMPRESSED_SIZE = 250 * 1000
const MAX_UNCOMPRESSED_SIZE = 2.5 * 1000 * 1000
......
......@@ -4,8 +4,7 @@ const execa = require('execa')
const fs = require('fs-extra')
const childProcess = require('child_process')
const { randomBytes } = require('crypto')
const { linkPackages } =
require('../../.github/actions/next-stats-action/src/prepare/repo-setup')()
const { linkPackages } = require('./link-packed-packages')
const yaml = require('js-yaml')
const {
getPnpmSecuritySettings,
......
const path = require('path')
const fs = require('fs')
const { existsSync } = require('fs')
/**
* Discovers the packed tarballs produced by `pack-for-isolated-tests` in the
* given repository checkout. Returns a Map from package name to tarball path.
*/
async function linkPackages({ repoDir }) {
/** @type {Map<string, string>} */
const pkgPaths = new Map()
let packageFolders
try {
packageFolders = await fs.promises.readdir(path.join(repoDir, 'packages'))
} catch (err) {
if (err.code === 'ENOENT') {
require('console').log('no packages to link')
return pkgPaths
}
throw err
}
for (const packageFolder of packageFolders) {
const packagePath = path.join(repoDir, 'packages', packageFolder)
const tarballPath = path.join(packagePath, 'packed.tgz')
const packageJsonPath = path.join(packagePath, 'package.json')
if (!existsSync(packageJsonPath) || !existsSync(tarballPath)) {
continue
}
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
pkgPaths.set(packageJson.name, tarballPath)
}
require('console').log(
`Found ${pkgPaths.size} packed tarballs:`,
Array.from(pkgPaths.keys()).join(', ')
)
return pkgPaths
}
module.exports = { linkPackages }
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