Unverified Commit 46c4f20c authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add custom profiler / tracer (#8378)

* Add custom profiler / tracer

This captures both client/production builds and everything before and after is cpu profiled, which makes sure that the whole process instead of just webpack is included in the final report.

* Update tests

* Update profiling-plugin.js

* Rename profiling-plugin.js to profiling-plugin.ts

* Update profiling-plugin.ts

* Update and rename profiling-plugin.ts to profiling-plugin.js

* Update webpack-config.ts

* Update profiling-plugin.js

* Add types

* Add missing type

* Add back TypeScript linting

* Remove tracing-js
parent ef13f5cc
...@@ -75,6 +75,13 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -75,6 +75,13 @@ export default async function build(dir: string, conf = null): Promise<void> {
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
const pagesDir = path.join(dir, 'pages') const pagesDir = path.join(dir, 'pages')
let tracer: any = null
if (config.experimental.profiling) {
const { createTrace } = require('./profiler/profiler.js')
tracer = createTrace(path.join(distDir, `profile-events.json`))
tracer.profiler.startProfiling()
}
const isFlyingShuttle = Boolean( const isFlyingShuttle = Boolean(
config.experimental.flyingShuttle && config.experimental.flyingShuttle &&
!process.env.__NEXT_BUILDER_EXPERIMENTAL_PAGE !process.env.__NEXT_BUILDER_EXPERIMENTAL_PAGE
...@@ -191,6 +198,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -191,6 +198,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
) )
const configs = await Promise.all([ const configs = await Promise.all([
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
tracer,
buildId, buildId,
isServer: false, isServer: false,
config, config,
...@@ -199,6 +207,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -199,6 +207,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
selectivePageBuilding, selectivePageBuilding,
}), }),
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
tracer,
buildId, buildId,
isServer: true, isServer: true,
config, config,
...@@ -528,4 +537,62 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -528,4 +537,62 @@ export default async function build(dir: string, conf = null): Promise<void> {
} }
printTreeView(Object.keys(allMappedPages), allPageInfos, isLikeServerless) printTreeView(Object.keys(allMappedPages), allPageInfos, isLikeServerless)
if (tracer) {
const parsedResults = await tracer.profiler.stopProfiling()
await new Promise(resolve => {
if (parsedResults === undefined) {
tracer.profiler.destroy()
tracer.trace.flush()
tracer.end(resolve)
return
}
const cpuStartTime = parsedResults.profile.startTime
const cpuEndTime = parsedResults.profile.endTime
tracer.trace.completeEvent({
name: 'TaskQueueManager::ProcessTaskFromWorkQueue',
id: ++tracer.counter,
cat: ['toplevel'],
ts: cpuStartTime,
args: {
src_file: '../../ipc/ipc_moji_bootstrap.cc',
src_func: 'Accept',
},
})
tracer.trace.completeEvent({
name: 'EvaluateScript',
id: ++tracer.counter,
cat: ['devtools.timeline'],
ts: cpuStartTime,
dur: cpuEndTime - cpuStartTime,
args: {
data: {
url: 'webpack',
lineNumber: 1,
columnNumber: 1,
frame: '0xFFF',
},
},
})
tracer.trace.instantEvent({
name: 'CpuProfile',
id: ++tracer.counter,
cat: ['disabled-by-default-devtools.timeline'],
ts: cpuEndTime,
args: {
data: {
cpuProfile: parsedResults.profile,
},
},
})
tracer.profiler.destroy()
tracer.trace.flush()
tracer.end(resolve)
})
}
} }
import path from 'path'
import mkdirp from 'mkdirp'
import fs from 'fs'
let inspector
try {
// eslint-disable-next-line node/no-unsupported-features/node-builtins
inspector = require('inspector')
} catch (e) {
console.log('Unable to CPU profile in < node 8.0')
}
class Profiler {
constructor (inspector) {
this.session = undefined
this.inspector = inspector
}
hasSession () {
return this.session !== undefined
}
startProfiling () {
if (this.inspector === undefined) {
return Promise.resolve()
}
try {
this.session = new inspector.Session()
this.session.connect()
} catch (_) {
this.session = undefined
return Promise.resolve()
}
return Promise.all([
this.sendCommand('Profiler.setSamplingInterval', {
interval: 100
}),
this.sendCommand('Profiler.enable'),
this.sendCommand('Profiler.start')
])
}
sendCommand (method, params) {
if (this.hasSession()) {
return new Promise((resolve, reject) => {
return this.session.post(method, params, (err, params) => {
if (err !== null) {
reject(err)
} else {
resolve(params)
}
})
})
} else {
return Promise.resolve()
}
}
destroy () {
if (this.hasSession()) {
this.session.disconnect()
}
return Promise.resolve()
}
stopProfiling () {
return this.sendCommand('Profiler.stop')
}
}
const { Tracer } = require('chrome-trace-event')
/**
* an object that wraps Tracer and Profiler with a counter
* @typedef {Object} Trace
* @property {Tracer} trace instance of Tracer
* @property {number} counter Counter
* @property {Profiler} profiler instance of Profiler
* @property {Function} end the end function
*/
/**
* @param {string} outputPath The location where to write the log.
* @returns {Trace} The trace object
*/
export const createTrace = outputPath => {
const trace = new Tracer({
noStream: true
})
const profiler = new Profiler(inspector)
if (/\/|\\/.test(outputPath)) {
const dirPath = path.dirname(outputPath)
mkdirp.sync(dirPath)
}
const fsStream = fs.createWriteStream(outputPath)
let counter = 0
trace.pipe(fsStream)
// These are critical events that need to be inserted so that tools like
// chrome dev tools can load the profile.
trace.instantEvent({
name: 'TracingStartedInPage',
id: ++counter,
cat: ['disabled-by-default-devtools.timeline'],
args: {
data: {
sessionId: '-1',
page: '0xfff',
frames: [
{
frame: '0xfff',
url: 'webpack',
name: ''
}
]
}
}
})
trace.instantEvent({
name: 'TracingStartedInBrowser',
id: ++counter,
cat: ['disabled-by-default-devtools.timeline'],
args: {
data: {
sessionId: '-1'
}
}
})
return {
trace,
counter,
profiler,
end: callback => {
// Wait until the write stream finishes.
fsStream.on('finish', () => {
callback()
})
// Tear down the readable trace stream.
trace.push(null)
}
}
}
...@@ -34,6 +34,8 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' ...@@ -34,6 +34,8 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin' import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin' import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index' import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
// @ts-ignore: JS file
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -53,7 +55,9 @@ export default async function getBaseWebpackConfig( ...@@ -53,7 +55,9 @@ export default async function getBaseWebpackConfig(
target = 'server', target = 'server',
entrypoints, entrypoints,
selectivePageBuilding = false, selectivePageBuilding = false,
tracer,
}: { }: {
tracer?: any
dev?: boolean dev?: boolean
isServer?: boolean isServer?: boolean
buildId: string buildId: string
...@@ -656,12 +660,9 @@ export default async function getBaseWebpackConfig( ...@@ -656,12 +660,9 @@ export default async function getBaseWebpackConfig(
clientManifest: config.experimental.granularChunks, clientManifest: config.experimental.granularChunks,
modern: config.experimental.modern, modern: config.experimental.modern,
}), }),
config.experimental.profiling && tracer &&
new webpack.debug.ProfilingPlugin({ new ProfilingPlugin({
outputPath: path.join( tracer,
distDir,
`profile-events-${isServer ? 'server' : 'client'}.json`
),
}), }),
!isServer && !isServer &&
useTypeScript && useTypeScript &&
......
// Copy of https://github.com/webpack/webpack/blob/master/lib/debug/ProfilingPlugin.js
// License:
/*
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Includes fix https://github.com/webpack/webpack/pull/9566
// Includes support for custom tracer that can capture across multiple builds
const pluginName = 'ProfilingPlugin'
export class ProfilingPlugin {
tracer: any
/**
* @param {ProfilingPluginOptions=} opts options object
*/
constructor(opts: { tracer: any }) {
this.tracer = opts.tracer
}
apply(compiler: any) {
const tracer = this.tracer
// Compiler Hooks
Object.keys(compiler.hooks).forEach(hookName => {
compiler.hooks[hookName].intercept(
makeInterceptorFor('Compiler', tracer)(hookName)
)
})
Object.keys(compiler.resolverFactory.hooks).forEach(hookName => {
compiler.resolverFactory.hooks[hookName].intercept(
makeInterceptorFor('Resolver', tracer)(hookName)
)
})
compiler.hooks.compilation.tap(
pluginName,
(
compilation: any,
{ normalModuleFactory, contextModuleFactory }: any
) => {
interceptAllHooksFor(compilation, tracer, 'Compilation')
interceptAllHooksFor(
normalModuleFactory,
tracer,
'Normal Module Factory'
)
interceptAllHooksFor(
contextModuleFactory,
tracer,
'Context Module Factory'
)
interceptAllParserHooks(normalModuleFactory, tracer)
interceptTemplateInstancesFrom(compilation, tracer)
}
)
}
}
const interceptTemplateInstancesFrom = (compilation: any, tracer: any) => {
const {
mainTemplate,
chunkTemplate,
hotUpdateChunkTemplate,
moduleTemplates,
} = compilation
const { javascript, webassembly } = moduleTemplates
;[
{
instance: mainTemplate,
name: 'MainTemplate',
},
{
instance: chunkTemplate,
name: 'ChunkTemplate',
},
{
instance: hotUpdateChunkTemplate,
name: 'HotUpdateChunkTemplate',
},
{
instance: javascript,
name: 'JavaScriptModuleTemplate',
},
{
instance: webassembly,
name: 'WebAssemblyModuleTemplate',
},
].forEach(templateObject => {
Object.keys(templateObject.instance.hooks).forEach(hookName => {
templateObject.instance.hooks[hookName].intercept(
makeInterceptorFor(templateObject.name, tracer)(hookName)
)
})
})
}
const interceptAllHooksFor = (instance: any, tracer: any, logLabel: any) => {
if (Reflect.has(instance, 'hooks')) {
Object.keys(instance.hooks).forEach(hookName => {
instance.hooks[hookName].intercept(
makeInterceptorFor(logLabel, tracer)(hookName)
)
})
}
}
const interceptAllParserHooks = (moduleFactory: any, tracer: any) => {
const moduleTypes = [
'javascript/auto',
'javascript/dynamic',
'javascript/esm',
'json',
'webassembly/experimental',
]
moduleTypes.forEach(moduleType => {
moduleFactory.hooks.parser
.for(moduleType)
.tap('ProfilingPlugin', (parser: any, parserOpts: any) => {
interceptAllHooksFor(parser, tracer, 'Parser')
})
})
}
const makeInterceptorFor = (instance: any, tracer: any) => (hookName: any) => ({
register: ({ name, type, context, fn }: any) => {
const newFn = makeNewProfiledTapFn(hookName, tracer, {
name,
type,
fn,
})
return {
name,
type,
context,
fn: newFn,
}
},
})
// TODO improve typing
/** @typedef {(...args: TODO[]) => void | Promise<TODO>} PluginFunction */
/**
* @param {string} hookName Name of the hook to profile.
* @param {Trace} tracer The trace object.
* @param {object} options Options for the profiled fn.
* @param {string} options.name Plugin name
* @param {string} options.type Plugin type (sync | async | promise)
* @param {PluginFunction} options.fn Plugin function
* @returns {PluginFunction} Chainable hooked function.
*/
const makeNewProfiledTapFn = (
hookName: any,
tracer: any,
{ name, type, fn }: any
) => {
const defaultCategory = ['blink.user_timing']
switch (type) {
case 'promise':
return (...args: any) => {
const id = ++tracer.counter
tracer.trace.begin({
name,
id,
cat: defaultCategory,
})
const promise = /** @type {Promise<*>} */ fn(...args)
return promise.then((r: any) => {
tracer.trace.end({
name,
id,
cat: defaultCategory,
})
return r
})
}
case 'async':
return (...args: any) => {
const id = ++tracer.counter
tracer.trace.begin({
name,
id,
cat: defaultCategory,
})
const callback = args.pop()
/* eslint-disable */
fn(...args, (...r: any) => {
tracer.trace.end({
name,
id,
cat: defaultCategory,
})
callback(...r)
})
/* eslint-enable */
}
case 'sync':
return (...args: any) => {
const id = ++tracer.counter
// Do not instrument ourself due to the CPU
// profile needing to be the last event in the trace.
if (name === pluginName) {
return fn(...args)
}
tracer.trace.begin({
name,
id,
cat: defaultCategory,
})
let r
try {
r = fn(...args)
} catch (error) {
tracer.trace.end({
name,
id,
cat: defaultCategory,
})
throw error
}
tracer.trace.end({
name,
id,
cat: defaultCategory,
})
return r
}
default:
break
}
}
...@@ -574,6 +574,10 @@ describe('Production Usage', () => { ...@@ -574,6 +574,10 @@ describe('Production Usage', () => {
} }
}) })
it('should not emit profiling events', async () => {
expect(existsSync(join(appDir, '.next', 'profile-events.json'))).toBe(false)
})
dynamicImportTests(context, (p, q) => renderViaHTTP(context.appPort, p, q)) dynamicImportTests(context, (p, q) => renderViaHTTP(context.appPort, p, q))
processEnv(context) processEnv(context)
......
...@@ -13,12 +13,9 @@ describe('Profiling Usage', () => { ...@@ -13,12 +13,9 @@ describe('Profiling Usage', () => {
describe('Profiling the build', () => { describe('Profiling the build', () => {
it('should emit files', async () => { it('should emit files', async () => {
expect( expect(fs.existsSync(join(appDir, '.next', 'profile-events.json'))).toBe(
fs.existsSync(join(appDir, '.next', 'profile-events-server.json')) true
).toBe(true) )
expect(
fs.existsSync(join(appDir, '.next', 'profile-events-client.json'))
).toBe(true)
}) })
}) })
}) })
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