2021-01-10 02:12:13 +01:00
|
|
|
import { tracer } from '../../tracer'
|
2021-01-18 17:38:00 +01:00
|
|
|
import { webpack, isWebpack5 } from 'next/dist/compiled/webpack/webpack'
|
2019-08-18 21:45:39 +02:00
|
|
|
|
|
|
|
const pluginName = 'ProfilingPlugin'
|
|
|
|
|
2021-01-10 02:12:13 +01:00
|
|
|
export const spans = new WeakMap()
|
2019-08-18 21:45:39 +02:00
|
|
|
|
2021-01-18 17:38:00 +01:00
|
|
|
function getNormalModuleLoaderHook(compilation: any) {
|
|
|
|
if (isWebpack5) {
|
|
|
|
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
|
|
|
|
return webpack.NormalModule.getCompilationHooks(compilation).loader
|
|
|
|
}
|
|
|
|
|
|
|
|
return compilation.hooks.normalModuleLoader
|
|
|
|
}
|
|
|
|
|
2021-01-10 02:12:13 +01:00
|
|
|
export class ProfilingPlugin {
|
2019-08-18 21:45:39 +02:00
|
|
|
apply(compiler: any) {
|
2021-01-10 02:12:13 +01:00
|
|
|
// Only enabled when instrumentation is loaded
|
2021-01-18 17:38:00 +01:00
|
|
|
const currentSpan = tracer.getCurrentSpan()
|
|
|
|
if (!currentSpan || !currentSpan.isRecording()) {
|
2021-01-10 02:12:13 +01:00
|
|
|
return
|
|
|
|
}
|
2019-08-18 21:45:39 +02:00
|
|
|
|
2021-01-10 02:12:13 +01:00
|
|
|
compiler.hooks.compile.tap(pluginName, () => {
|
|
|
|
const span = tracer.startSpan('webpack-compile', {
|
|
|
|
attributes: { name: compiler.name },
|
|
|
|
})
|
|
|
|
spans.set(compiler, span)
|
2019-08-18 21:45:39 +02:00
|
|
|
})
|
2021-01-10 02:12:13 +01:00
|
|
|
compiler.hooks.done.tap(pluginName, () => {
|
|
|
|
spans.get(compiler).end()
|
2019-08-18 21:45:39 +02:00
|
|
|
})
|
2021-01-10 02:12:13 +01:00
|
|
|
compiler.hooks.compilation.tap(pluginName, (compilation: any) => {
|
|
|
|
compilation.hooks.buildModule.tap(pluginName, (module: any) => {
|
|
|
|
tracer.withSpan(spans.get(compiler), () => {
|
|
|
|
const span = tracer.startSpan('build-module')
|
|
|
|
span.setAttribute('name', module.userRequest)
|
|
|
|
spans.set(module, span)
|
|
|
|
})
|
|
|
|
})
|
2019-08-18 21:45:39 +02:00
|
|
|
|
2021-01-18 17:38:00 +01:00
|
|
|
getNormalModuleLoaderHook(compilation).tap(
|
2021-01-10 02:12:13 +01:00
|
|
|
pluginName,
|
|
|
|
(loaderContext: any, module: any) => {
|
|
|
|
const parentSpan = spans.get(module)
|
|
|
|
loaderContext.currentTraceSpan = parentSpan
|
|
|
|
}
|
2019-08-18 21:45:39 +02:00
|
|
|
)
|
|
|
|
|
2021-01-10 02:12:13 +01:00
|
|
|
compilation.hooks.succeedModule.tap(pluginName, (module: any) => {
|
|
|
|
spans.get(module).end()
|
2019-08-18 21:45:39 +02:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|