Unverified Commit de670b38 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Do Not Rely on Module State (#8968)

* Do Not Rely on Module State

* Update storage.ts
parent ac42beae
...@@ -25,12 +25,12 @@ import loadConfig, { ...@@ -25,12 +25,12 @@ import loadConfig, {
isTargetLikeServerless, isTargetLikeServerless,
} from '../next-server/server/config' } from '../next-server/server/config'
import { import {
recordBuildDuration, eventBuildDuration,
recordBuildOptimize, eventBuildOptimize,
recordNextPlugins, eventNextPlugins,
recordVersion, eventVersion,
} from '../telemetry/events' } from '../telemetry/events'
import { setDistDir as setTelemetryDir } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import { CompilerResult, runCompiler } from './compiler' import { CompilerResult, runCompiler } from './compiler'
import { createEntrypoints, createPagesMapping } from './entries' import { createEntrypoints, createPagesMapping } from './entries'
import { generateBuildId } from './generate-build-id' import { generateBuildId } from './generate-build-id'
...@@ -91,7 +91,9 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -91,7 +91,9 @@ export default async function build(dir: string, conf = null): Promise<void> {
const { target } = config const { target } = config
const buildId = await generateBuildId(config.generateBuildId, nanoid) const buildId = await generateBuildId(config.generateBuildId, nanoid)
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
setTelemetryDir(distDir)
const telemetry = new Telemetry({ distDir })
const publicDir = path.join(dir, 'public') const publicDir = path.join(dir, 'public')
const pagesDir = findPagesDir(dir) const pagesDir = findPagesDir(dir)
let publicFiles: string[] = [] let publicFiles: string[] = []
...@@ -99,8 +101,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -99,8 +101,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
let backgroundWork: (Promise<any> | undefined)[] = [] let backgroundWork: (Promise<any> | undefined)[] = []
backgroundWork.push( backgroundWork.push(
recordVersion({ cliCommand: 'build' }), telemetry.record(eventVersion({ cliCommand: 'build' })),
recordNextPlugins(path.resolve(dir)) eventNextPlugins(path.resolve(dir)).then(events => telemetry.record(events))
) )
await verifyTypeScriptSetup(dir, pagesDir) await verifyTypeScriptSetup(dir, pagesDir)
...@@ -273,10 +275,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -273,10 +275,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
} else { } else {
console.log(chalk.green('Compiled successfully.\n')) console.log(chalk.green('Compiled successfully.\n'))
backgroundWork.push( backgroundWork.push(
recordBuildDuration({ telemetry.record(
totalPageCount: pagePaths.length, eventBuildDuration({
durationInSeconds: webpackBuildEnd[0], totalPageCount: pagePaths.length,
}) durationInSeconds: webpackBuildEnd[0],
})
)
) )
} }
...@@ -572,12 +576,14 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -572,12 +576,14 @@ export default async function build(dir: string, conf = null): Promise<void> {
const analysisEnd = process.hrtime(analysisBegin) const analysisEnd = process.hrtime(analysisBegin)
backgroundWork.push( backgroundWork.push(
recordBuildOptimize({ telemetry.record(
durationInSeconds: analysisEnd[0], eventBuildOptimize({
totalPageCount: pagePaths.length, durationInSeconds: analysisEnd[0],
staticPageCount: staticPages.size, totalPageCount: pagePaths.length,
ssrPageCount: pagePaths.length - staticPages.size, staticPageCount: staticPages.size,
}) ssrPageCount: pagePaths.length - staticPages.size,
})
)
) )
if (sprPages.size > 0) { if (sprPages.size > 0) {
......
...@@ -3,7 +3,7 @@ import chalk from 'chalk' ...@@ -3,7 +3,7 @@ import chalk from 'chalk'
import arg from 'next/dist/compiled/arg/index.js' import arg from 'next/dist/compiled/arg/index.js'
import { cliCommand } from '../bin/next' import { cliCommand } from '../bin/next'
import { setTelemetryEnabled, isTelemetryEnabled } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
const nextTelemetry: cliCommand = argv => { const nextTelemetry: cliCommand = argv => {
const args = arg( const args = arg(
...@@ -35,16 +35,18 @@ const nextTelemetry: cliCommand = argv => { ...@@ -35,16 +35,18 @@ const nextTelemetry: cliCommand = argv => {
return return
} }
let isEnabled = isTelemetryEnabled() const telemetry = new Telemetry({ distDir: process.cwd() })
let isEnabled = telemetry.isEnabled
if (args['--enable'] || args._[0] === 'enable') { if (args['--enable'] || args._[0] === 'enable') {
setTelemetryEnabled(true) telemetry.setEnabled(true)
console.log(chalk.cyan('Success!')) console.log(chalk.cyan('Success!'))
console.log() console.log()
isEnabled = true isEnabled = true
} else if (args['--disable'] || args._[0] === 'disable') { } else if (args['--disable'] || args._[0] === 'disable') {
setTelemetryEnabled(false) telemetry.setEnabled(false)
if (isEnabled) { if (isEnabled) {
console.log(chalk.cyan('Your preference has been saved.')) console.log(chalk.cyan('Your preference has been saved.'))
} else { } else {
......
...@@ -25,8 +25,8 @@ import { ...@@ -25,8 +25,8 @@ import {
import loadConfig, { import loadConfig, {
isTargetLikeServerless, isTargetLikeServerless,
} from '../next-server/server/config' } from '../next-server/server/config'
import { recordVersion } from '../telemetry/events' import { eventVersion } from '../telemetry/events'
import { setDistDir as setTelemetryDir } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
const mkdirp = promisify(mkdirpModule) const mkdirp = promisify(mkdirpModule)
const copyFile = promisify(copyFileOrig) const copyFile = promisify(copyFileOrig)
...@@ -94,8 +94,8 @@ export default async function( ...@@ -94,8 +94,8 @@ export default async function(
const threads = options.threads || Math.max(cpus().length - 1, 1) const threads = options.threads || Math.max(cpus().length - 1, 1)
const distDir = join(dir, nextConfig.distDir) const distDir = join(dir, nextConfig.distDir)
if (!options.buildExport) { if (!options.buildExport) {
setTelemetryDir(distDir) const telemetry = new Telemetry({ distDir })
recordVersion({ cliCommand: 'export' }) telemetry.record(eventVersion({ cliCommand: 'export' }))
} }
const subFolders = nextConfig.exportTrailingSlash const subFolders = nextConfig.exportTrailingSlash
......
...@@ -22,8 +22,8 @@ import { ...@@ -22,8 +22,8 @@ import {
import Server, { ServerConstructor } from '../next-server/server/next-server' import Server, { ServerConstructor } from '../next-server/server/next-server'
import { normalizePagePath } from '../next-server/server/normalize-page-path' import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { route } from '../next-server/server/router' import { route } from '../next-server/server/router'
import { recordVersion } from '../telemetry/events' import { eventVersion } from '../telemetry/events'
import { setDistDir as setTelemetryDir } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import ErrorDebug from './error-debug' import ErrorDebug from './error-debug'
import HotReloader from './hot-reloader' import HotReloader from './hot-reloader'
import { findPageFile } from './lib/find-page-file' import { findPageFile } from './lib/find-page-file'
...@@ -206,8 +206,8 @@ export default class DevServer extends Server { ...@@ -206,8 +206,8 @@ export default class DevServer extends Server {
await this.startWatcher() await this.startWatcher()
this.setDevReady!() this.setDevReady!()
setTelemetryDir(this.distDir) const telemetry = new Telemetry({ distDir: this.distDir })
recordVersion({ cliCommand: 'dev' }) telemetry.record(eventVersion({ cliCommand: 'dev' }))
} }
protected async close() { protected async close() {
......
import { record } from '../storage'
const EVENT_BUILD_DURATION = 'NEXT_BUILD_COMPLETED' const EVENT_BUILD_DURATION = 'NEXT_BUILD_COMPLETED'
type EventBuildCompleted = { type EventBuildCompleted = {
durationInSeconds: number durationInSeconds: number
totalPageCount: number totalPageCount: number
} }
export function recordBuildDuration(event: EventBuildCompleted) { export function eventBuildDuration(
return record({ event: EventBuildCompleted
): { eventName: string; payload: EventBuildCompleted } {
return {
eventName: EVENT_BUILD_DURATION, eventName: EVENT_BUILD_DURATION,
payload: event, payload: event,
}) }
} }
const EVENT_BUILD_OPTIMIZE = 'NEXT_BUILD_OPTIMIZED' const EVENT_BUILD_OPTIMIZE = 'NEXT_BUILD_OPTIMIZED'
...@@ -21,9 +21,11 @@ type EventBuildOptimized = { ...@@ -21,9 +21,11 @@ type EventBuildOptimized = {
ssrPageCount: number ssrPageCount: number
} }
export function recordBuildOptimize(event: EventBuildOptimized) { export function eventBuildOptimize(
return record({ event: EventBuildOptimized
): { eventName: string; payload: EventBuildOptimized } {
return {
eventName: EVENT_BUILD_OPTIMIZE, eventName: EVENT_BUILD_OPTIMIZE,
payload: event, payload: event,
}) }
} }
import { record } from '../storage'
import findUp from 'find-up' import findUp from 'find-up'
const EVENT_PLUGIN_PRESENT = 'NEXT_PACKAGE_DETECTED' const EVENT_PLUGIN_PRESENT = 'NEXT_PACKAGE_DETECTED'
...@@ -159,32 +158,34 @@ const plugins = [ ...@@ -159,32 +158,34 @@ const plugins = [
'@apollo/react-ssr', '@apollo/react-ssr',
] ]
export async function recordNextPlugins(dir: string) { export async function eventNextPlugins(
dir: string
): Promise<Array<{ eventName: string; payload: EventPackageDetected }>> {
try { try {
const packageJsonPath = await findUp('package.json', { cwd: dir }) const packageJsonPath = await findUp('package.json', { cwd: dir })
if (!packageJsonPath) { if (!packageJsonPath) {
return return []
} }
const { dependencies = {}, devDependencies = {} } = require(packageJsonPath) const { dependencies = {}, devDependencies = {} } = require(packageJsonPath)
return record( return (plugins
(plugins .map(plugin => {
.map(plugin => { const version = dependencies[plugin] || devDependencies[plugin]
const version = dependencies[plugin] || devDependencies[plugin] if (version) {
if (version) { return { pluginName: plugin, pluginVersion: version }
return { pluginName: plugin, pluginVersion: version } }
} })
}) .filter(Boolean) as {
.filter(Boolean) as { pluginName: string
pluginName: string pluginVersion: string
pluginVersion: string }[]).map(({ pluginName, pluginVersion }) => ({
}[]).map(({ pluginName, pluginVersion }) => ({ eventName: EVENT_PLUGIN_PRESENT,
eventName: EVENT_PLUGIN_PRESENT, payload: {
payload: { packageName: pluginName,
packageName: pluginName, packageVersion: pluginVersion,
packageVersion: pluginVersion, } as EventPackageDetected,
} as EventPackageDetected, }))
})) } catch (_) {
) return []
} catch (_) {} }
} }
import { record } from '../storage'
const EVENT_VERSION = 'NEXT_CLI_SESSION_STARTED' const EVENT_VERSION = 'NEXT_CLI_SESSION_STARTED'
type EventCliSessionStarted = { type EventCliSessionStarted = {
...@@ -8,20 +6,22 @@ type EventCliSessionStarted = { ...@@ -8,20 +6,22 @@ type EventCliSessionStarted = {
cliCommand: string cliCommand: string
} }
export function recordVersion( export function eventVersion(
event: Omit<EventCliSessionStarted, 'nextVersion' | 'nodeVersion'> event: Omit<EventCliSessionStarted, 'nextVersion' | 'nodeVersion'>
) { ): { eventName: string; payload: EventCliSessionStarted }[] {
// This should be an invariant, if it fails our build tooling is broken. // This should be an invariant, if it fails our build tooling is broken.
if (typeof process.env.__NEXT_VERSION !== 'string') { if (typeof process.env.__NEXT_VERSION !== 'string') {
return Promise.resolve() return []
} }
return record({ return [
eventName: EVENT_VERSION, {
payload: { eventName: EVENT_VERSION,
nextVersion: process.env.__NEXT_VERSION, payload: {
nodeVersion: process.version, nextVersion: process.env.__NEXT_VERSION,
cliCommand: event.cliCommand, nodeVersion: process.version,
} as EventCliSessionStarted, cliCommand: event.cliCommand,
}) } as EventCliSessionStarted,
},
]
} }
import { execSync } from 'child_process' import { execSync } from 'child_process'
import { computeHash } from './storage'
// Q: Why does Next.js need a project ID? Why is it looking at my git remote? // Q: Why does Next.js need a project ID? Why is it looking at my git remote?
// A: // A:
...@@ -28,13 +27,6 @@ function _getProjectIdByGit() { ...@@ -28,13 +27,6 @@ function _getProjectIdByGit() {
} }
} }
export function getProjectId(): string { export function getRawProjectId(): string {
const projectId = return _getProjectIdByGit() || process.env.REPOSITORY_URL || process.cwd()
_getProjectIdByGit() || process.env.REPOSITORY_URL || process.cwd()
// Compute a one-way, salted hash of the project ID. This value cannot be
// reversed.
// See the top of the file for a more detailed reason why we ask for this
// data.
return computeHash(projectId.trim().toLowerCase()) || ''
} }
This diff is collapsed.
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