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,11 +275,13 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -273,11 +275,13 @@ 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(
eventBuildDuration({
totalPageCount: pagePaths.length, totalPageCount: pagePaths.length,
durationInSeconds: webpackBuildEnd[0], durationInSeconds: webpackBuildEnd[0],
}) })
) )
)
} }
const postBuildSpinner = createSpinner({ const postBuildSpinner = createSpinner({
...@@ -572,13 +576,15 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -572,13 +576,15 @@ 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(
eventBuildOptimize({
durationInSeconds: analysisEnd[0], durationInSeconds: analysisEnd[0],
totalPageCount: pagePaths.length, totalPageCount: pagePaths.length,
staticPageCount: staticPages.size, staticPageCount: staticPages.size,
ssrPageCount: pagePaths.length - staticPages.size, ssrPageCount: pagePaths.length - staticPages.size,
}) })
) )
)
if (sprPages.size > 0) { if (sprPages.size > 0) {
const finalDynamicRoutes: PrerenderManifest['dynamicRoutes'] = {} const finalDynamicRoutes: PrerenderManifest['dynamicRoutes'] = {}
......
...@@ -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,16 +158,17 @@ const plugins = [ ...@@ -159,16 +158,17 @@ 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) {
...@@ -185,6 +185,7 @@ export async function recordNextPlugins(dir: string) { ...@@ -185,6 +185,7 @@ export async function recordNextPlugins(dir: string) {
packageVersion: pluginVersion, packageVersion: pluginVersion,
} as EventPackageDetected, } as EventPackageDetected,
})) }))
) } catch (_) {
} catch (_) {} return []
}
} }
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, eventName: EVENT_VERSION,
payload: { payload: {
nextVersion: process.env.__NEXT_VERSION, nextVersion: process.env.__NEXT_VERSION,
nodeVersion: process.version, nodeVersion: process.version,
cliCommand: event.cliCommand, cliCommand: event.cliCommand,
} as EventCliSessionStarted, } 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()) || ''
} }
...@@ -7,13 +7,7 @@ import path from 'path' ...@@ -7,13 +7,7 @@ import path from 'path'
import { getAnonymousMeta } from './anonymous-meta' import { getAnonymousMeta } from './anonymous-meta'
import * as ciEnvironment from './ci-info' import * as ciEnvironment from './ci-info'
import { _postPayload } from './post-payload' import { _postPayload } from './post-payload'
import { getProjectId } from './project-id' import { getRawProjectId } from './project-id'
let distDir: string | undefined
let config: Conf<any> | undefined
let projectId: string | undefined
let randomRunId: string | undefined
// This is the key that stores whether or not telemetry is enabled or disabled. // This is the key that stores whether or not telemetry is enabled or disabled.
const TELEMETRY_KEY_ENABLED = 'telemetry.enabled' const TELEMETRY_KEY_ENABLED = 'telemetry.enabled'
...@@ -29,16 +23,40 @@ const TELEMETRY_KEY_ID = `telemetry.anonymousId` ...@@ -29,16 +23,40 @@ const TELEMETRY_KEY_ID = `telemetry.anonymousId`
// This is the cryptographic salt that is included within every hashed value. // This is the cryptographic salt that is included within every hashed value.
// This salt value is never sent to us, ensuring privacy and the one-way nature // This salt value is never sent to us, ensuring privacy and the one-way nature
// of the hash (prevents dictionary lookups of pre-computed hashes). // of the hash (prevents dictionary lookups of pre-computed hashes).
// See the `computeHash` function. // See the `oneWayHash` function.
const TELEMETRY_KEY_SALT = `telemetry.salt` const TELEMETRY_KEY_SALT = `telemetry.salt`
const { NEXT_TELEMETRY_DISABLED, NEXT_TELEMETRY_DEBUG } = process.env const { NEXT_TELEMETRY_DISABLED, NEXT_TELEMETRY_DEBUG } = process.env
let isDisabled: boolean = !!NEXT_TELEMETRY_DISABLED type TelemetryEvent = { eventName: string; payload: object }
type EventContext = {
anonymousId: string
projectId: string
sessionId: string
}
type EventMeta = { [key: string]: unknown }
type EventBatchShape = {
eventName: string
fields: object
}
export class Telemetry {
private conf: Conf<any>
private sessionId: string
private rawProjectId: string
constructor({ distDir }: { distDir: string }) {
const storageDirectory = getStorageDirectory(distDir)
this.conf = new Conf({ projectName: 'nextjs', cwd: storageDirectory })
this.sessionId = randomBytes(32).toString('hex')
this.rawProjectId = getRawProjectId()
this.notify()
}
function notify() { private notify = () => {
// No notification needed if telemetry is not enabled if (this.isDisabled) {
if (!config || isDisabled) {
return return
} }
...@@ -46,11 +64,10 @@ function notify() { ...@@ -46,11 +64,10 @@ function notify() {
// don't need to constantly annoy them about it. // don't need to constantly annoy them about it.
// We will re-inform users about the telemetry if significant changes are // We will re-inform users about the telemetry if significant changes are
// ever made. // ever made.
if (config.get(TELEMETRY_KEY_NOTIFY_DATE, '')) { if (this.conf.get(TELEMETRY_KEY_NOTIFY_DATE, '')) {
return return
} }
this.conf.set(TELEMETRY_KEY_NOTIFY_DATE, Date.now().toString())
config.set(TELEMETRY_KEY_NOTIFY_DATE, Date.now().toString())
console.log( console.log(
`${chalk.magenta.bold( `${chalk.magenta.bold(
...@@ -65,92 +82,93 @@ function notify() { ...@@ -65,92 +82,93 @@ function notify() {
) )
console.log(chalk.cyan('https://nextjs.org/telemetry')) console.log(chalk.cyan('https://nextjs.org/telemetry'))
console.log() console.log()
}
function setup() {
if (config) {
return
} }
const cwd = get anonymousId(): string {
(ciEnvironment.isCI || isDockerFunction()) && distDir const val = this.conf.get(TELEMETRY_KEY_ID)
? path.join(distDir, 'cache') if (val) {
: undefined return val
config = new Conf({ projectName: 'nextjs', cwd })
let anonymousId = config.get(TELEMETRY_KEY_ID)
if (!anonymousId) {
config.set(
TELEMETRY_KEY_ID,
(anonymousId = randomBytes(32).toString('hex'))
)
} }
if (!config.get(TELEMETRY_KEY_SALT)) { const generated = randomBytes(32).toString('hex')
config.set(TELEMETRY_KEY_SALT, randomBytes(16).toString('hex')) this.conf.set(TELEMETRY_KEY_ID, generated)
return generated
} }
projectId = getProjectId() get salt(): string {
randomRunId = randomBytes(8).toString('hex') const val = this.conf.get(TELEMETRY_KEY_SALT)
if (val) {
if (config.get(TELEMETRY_KEY_ENABLED, true) === false) { return val
isDisabled = true
} }
notify() const generated = randomBytes(16).toString('hex')
} this.conf.set(TELEMETRY_KEY_SALT, generated)
return generated
}
export function setDistDir(_distDir: string) { private get isDisabled(): boolean {
distDir = _distDir if (!!NEXT_TELEMETRY_DISABLED) {
} return true
}
return this.conf.get(TELEMETRY_KEY_ENABLED, true) === false
}
export function computeHash(payload: BinaryLike): string | null { setEnabled = (_enabled: boolean) => {
setup() const enabled = !!_enabled
this.conf.set(TELEMETRY_KEY_ENABLED, enabled)
}
const salt = config!.get(TELEMETRY_KEY_SALT) get isEnabled(): boolean {
if (!salt) { return this.conf.get(TELEMETRY_KEY_ENABLED, true) !== false
return null
} }
oneWayHash = (payload: BinaryLike): string => {
const hash = createHash('sha256') const hash = createHash('sha256')
// Always prepend the payload value with salt. This ensures the hash is truly // Always prepend the payload value with salt. This ensures the hash is truly
// one-way. // one-way.
hash.update(salt) hash.update(this.salt)
// Update is an append operation, not a replacement. The salt from the prior // Update is an append operation, not a replacement. The salt from the prior
// update is still present! // update is still present!
hash.update(payload) hash.update(payload)
return hash.digest('hex') return hash.digest('hex')
} }
export function setTelemetryEnabled(_enabled: boolean) {
setup()
const enabled = !!_enabled private get projectId(): string {
config!.set(TELEMETRY_KEY_ENABLED, enabled) return this.oneWayHash(this.rawProjectId)
isDisabled = !enabled }
}
export function isTelemetryEnabled(): boolean { record = (
setup() _events: TelemetryEvent | TelemetryEvent[]
): Promise<{
isFulfilled: boolean
isRejected: boolean
value?: any
reason?: any
}> => {
const _this = this
// pseudo try-catch
async function wrapper() {
return await _this.submitRecord(_events)
}
return config!.get(TELEMETRY_KEY_ENABLED, true) !== false return wrapper()
} .then(value => ({
isFulfilled: true,
isRejected: false,
value,
}))
.catch(reason => ({
isFulfilled: false,
isRejected: true,
reason,
}))
}
type TelemetryEvent = { eventName: string; payload: object } private submitRecord = (
type EventContext = { _events: TelemetryEvent | TelemetryEvent[]
anonymousId: string ): Promise<any> => {
projectId: string
sessionId: string
}
type EventMeta = { [key: string]: unknown }
type EventBatchShape = {
eventName: string
fields: object
}
function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> {
let events: TelemetryEvent[] let events: TelemetryEvent[]
if (Array.isArray(_events)) { if (Array.isArray(_events)) {
events = _events events = _events
...@@ -162,8 +180,6 @@ function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> { ...@@ -162,8 +180,6 @@ function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> {
return Promise.resolve() return Promise.resolve()
} }
setup()
if (NEXT_TELEMETRY_DEBUG) { if (NEXT_TELEMETRY_DEBUG) {
// Print to standard error to simplify selecting the output // Print to standard error to simplify selecting the output
events.forEach(({ eventName, payload }) => events.forEach(({ eventName, payload }) =>
...@@ -177,19 +193,14 @@ function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> { ...@@ -177,19 +193,14 @@ function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> {
} }
// Skip recording telemetry if the feature is disabled // Skip recording telemetry if the feature is disabled
if (isDisabled) { if (this.isDisabled) {
return Promise.resolve()
}
const anonymousId = config!.get(TELEMETRY_KEY_ID)
if (!anonymousId) {
return Promise.resolve() return Promise.resolve()
} }
const context: EventContext = { const context: EventContext = {
anonymousId: anonymousId, anonymousId: this.anonymousId,
projectId: projectId!, projectId: this.projectId,
sessionId: randomRunId!, sessionId: this.sessionId,
} }
const meta: EventMeta = getAnonymousMeta() const meta: EventMeta = getAnonymousMeta()
return _postPayload(`https://telemetry.nextjs.org/api/v1/record`, { return _postPayload(`https://telemetry.nextjs.org/api/v1/record`, {
...@@ -200,30 +211,15 @@ function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> { ...@@ -200,30 +211,15 @@ function _record(_events: TelemetryEvent | TelemetryEvent[]): Promise<any> {
fields: payload, fields: payload,
})) as Array<EventBatchShape>, })) as Array<EventBatchShape>,
}) })
}
} }
export function record( function getStorageDirectory(distDir: string): string | undefined {
_events: TelemetryEvent | TelemetryEvent[] const isLikelyEphemeral = ciEnvironment.isCI || isDockerFunction()
): Promise<{
isFulfilled: boolean if (isLikelyEphemeral) {
isRejected: boolean return path.join(distDir, 'cache')
value?: any
reason?: any
}> {
// pseudo try-catch
async function wrapper() {
return await _record(_events)
} }
return wrapper() return undefined
.then(value => ({
isFulfilled: true,
isRejected: false,
value,
}))
.catch(reason => ({
isFulfilled: false,
isRejected: true,
reason,
}))
} }
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