Unverified Commit 90ad2cbc authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Update profiling approach to cover webpack runs (#20900)

parent 8bdff57b
// Disable automatic instrumentation
process.env.OTEL_NO_PATCH_MODULES = '*'
const { NodeTracerProvider } = require('@opentelemetry/node') const { NodeTracerProvider } = require('@opentelemetry/node')
const { BatchSpanProcessor } = require('@opentelemetry/tracing') const { SimpleSpanProcessor } = require('@opentelemetry/tracing')
const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin') const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin')
const tracerProvider = new NodeTracerProvider() const tracerProvider = new NodeTracerProvider({
// All automatic instrumentation plugins have to be disabled as it affects worker_thread/child_process bootup performance
plugins: {
mongodb: { enabled: false, path: '@opentelemetry/plugin-mongodb' },
grpc: { enabled: false, path: '@opentelemetry/plugin-grpc' },
'@grpc/grpc-js': { enabled: false, path: '@opentelemetry/plugin-grpc-js' },
http: { enabled: false, path: '@opentelemetry/plugin-http' },
https: { enabled: false, path: '@opentelemetry/plugin-https' },
mysql: { enabled: false, path: '@opentelemetry/plugin-mysql' },
pg: { enabled: false, path: '@opentelemetry/plugin-pg' },
redis: { enabled: false, path: '@opentelemetry/plugin-redis' },
ioredis: { enabled: false, path: '@opentelemetry/plugin-ioredis' },
'pg-pool': { enabled: false, path: '@opentelemetry/plugin-pg-pool' },
express: { enabled: false, path: '@opentelemetry/plugin-express' },
'@hapi/hapi': {
enabled: false,
path: '@opentelemetry/hapi-instrumentation',
},
koa: { enabled: false, path: '@opentelemetry/koa-instrumentation' },
dns: { enabled: false, path: '@opentelemetry/plugin-dns' },
},
})
tracerProvider.addSpanProcessor( tracerProvider.addSpanProcessor(
new BatchSpanProcessor( new SimpleSpanProcessor(
new ZipkinExporter({ new ZipkinExporter({
serviceName: 'next-js', serviceName: 'next-js',
}) })
......
This diff is collapsed.
...@@ -28,6 +28,8 @@ import { BuildManifest } from '../next-server/server/get-page-files' ...@@ -28,6 +28,8 @@ import { BuildManifest } from '../next-server/server/get-page-files'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import { UnwrapPromise } from '../lib/coalesced-function' import { UnwrapPromise } from '../lib/coalesced-function'
import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
import opentelemetryApi from '@opentelemetry/api'
import { tracer, traceAsyncFn } from './tracer'
const fileGzipStats: { [k: string]: Promise<number> } = {} const fileGzipStats: { [k: string]: Promise<number> } = {}
const fsStatGzip = (file: string) => { const fsStatGzip = (file: string) => {
...@@ -713,7 +715,8 @@ export async function isPageStatic( ...@@ -713,7 +715,8 @@ export async function isPageStatic(
serverBundle: string, serverBundle: string,
runtimeEnvConfig: any, runtimeEnvConfig: any,
locales?: string[], locales?: string[],
defaultLocale?: string defaultLocale?: string,
spanContext?: any
): Promise<{ ): Promise<{
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean isAmpOnly?: boolean
...@@ -725,12 +728,27 @@ export async function isPageStatic( ...@@ -725,12 +728,27 @@ export async function isPageStatic(
prerenderFallback?: boolean | 'blocking' prerenderFallback?: boolean | 'blocking'
isNextImageImported?: boolean isNextImageImported?: boolean
}> { }> {
return opentelemetryApi.context.with(
opentelemetryApi.propagation.extract(
opentelemetryApi.context.active(),
spanContext
),
() => {
return traceAsyncFn(
tracer.startSpan('is-page-static-utils'),
async () => {
try { try {
require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig) require('../next-server/lib/runtime-config').setConfig(
runtimeEnvConfig
)
const mod = await require(serverBundle) const mod = await require(serverBundle)
const Comp = await (mod.default || mod) const Comp = await (mod.default || mod)
if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') { if (
!Comp ||
!isValidElementType(Comp) ||
typeof Comp === 'string'
) {
throw new Error('INVALID_DEFAULT_EXPORT') throw new Error('INVALID_DEFAULT_EXPORT')
} }
...@@ -816,7 +834,8 @@ export async function isPageStatic( ...@@ -816,7 +834,8 @@ export async function isPageStatic(
const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED
const config = mod.config || {} const config = mod.config || {}
return { return {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps, isStatic:
!hasStaticProps && !hasGetInitialProps && !hasServerProps,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true, isAmpOnly: config.amp === true,
prerenderRoutes, prerenderRoutes,
...@@ -830,6 +849,10 @@ export async function isPageStatic( ...@@ -830,6 +849,10 @@ export async function isPageStatic(
if (err.code === 'MODULE_NOT_FOUND') return {} if (err.code === 'MODULE_NOT_FOUND') return {}
throw err throw err
} }
}
)
}
)
} }
export async function hasCustomGetInitialProps( export async function hasCustomGetInitialProps(
......
...@@ -193,7 +193,6 @@ export default async function getBaseWebpackConfig( ...@@ -193,7 +193,6 @@ export default async function getBaseWebpackConfig(
dev = false, dev = false,
isServer = false, isServer = false,
pagesDir, pagesDir,
tracer,
target = 'server', target = 'server',
reactProductionProfiling = false, reactProductionProfiling = false,
entrypoints, entrypoints,
...@@ -205,7 +204,6 @@ export default async function getBaseWebpackConfig( ...@@ -205,7 +204,6 @@ export default async function getBaseWebpackConfig(
isServer?: boolean isServer?: boolean
pagesDir: string pagesDir: string
target?: string target?: string
tracer?: any
reactProductionProfiling?: boolean reactProductionProfiling?: boolean
entrypoints: WebpackEntrypoints entrypoints: WebpackEntrypoints
rewrites: Rewrite[] rewrites: Rewrite[]
...@@ -1078,10 +1076,7 @@ export default async function getBaseWebpackConfig( ...@@ -1078,10 +1076,7 @@ export default async function getBaseWebpackConfig(
buildId, buildId,
rewrites, rewrites,
}), }),
tracer && new ProfilingPlugin(),
new ProfilingPlugin({
tracer,
}),
config.experimental.optimizeFonts && config.experimental.optimizeFonts &&
!dev && !dev &&
isServer && isServer &&
......
...@@ -22,6 +22,8 @@ export default function makeLoader(callback) { ...@@ -22,6 +22,8 @@ export default function makeLoader(callback) {
} }
async function loader(source, inputSourceMap, overrides) { async function loader(source, inputSourceMap, overrides) {
// Provided by profiling-plugin.ts
return tracer.withSpan(this.currentTraceSpan, () => {
const span = tracer.startSpan('babel-loader') const span = tracer.startSpan('babel-loader')
return traceAsyncFn(span, async () => { return traceAsyncFn(span, async () => {
const filename = this.resourcePath const filename = this.resourcePath
...@@ -165,4 +167,5 @@ async function loader(source, inputSourceMap, overrides) { ...@@ -165,4 +167,5 @@ async function loader(source, inputSourceMap, overrides) {
// If the file was ignored, pass through the original content. // If the file was ignored, pass through the original content.
return [source, inputSourceMap] return [source, inputSourceMap]
}) })
})
} }
import { loader } from 'webpack'
import loaderUtils from 'loader-utils' import loaderUtils from 'loader-utils'
import { tracer, traceFn } from '../../tracer' import { tracer, traceFn } from '../../tracer'
...@@ -7,7 +6,9 @@ export type ClientPagesLoaderOptions = { ...@@ -7,7 +6,9 @@ export type ClientPagesLoaderOptions = {
page: string page: string
} }
const nextClientPagesLoader: loader.Loader = function () { // this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
function nextClientPagesLoader(this: any) {
return tracer.withSpan(this.currentTraceSpan, () => {
const span = tracer.startSpan('next-client-pages-loader') const span = tracer.startSpan('next-client-pages-loader')
return traceFn(span, () => { return traceFn(span, () => {
const { absolutePagePath, page } = loaderUtils.getOptions( const { absolutePagePath, page } = loaderUtils.getOptions(
...@@ -28,6 +29,7 @@ const nextClientPagesLoader: loader.Loader = function () { ...@@ -28,6 +29,7 @@ const nextClientPagesLoader: loader.Loader = function () {
]); ]);
` `
}) })
})
} }
export default nextClientPagesLoader export default nextClientPagesLoader
...@@ -15,7 +15,7 @@ import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin' ...@@ -15,7 +15,7 @@ import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { Rewrite } from '../../../lib/load-custom-routes' import { Rewrite } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../../../next-server/lib/router/utils' import { getSortedRoutes } from '../../../next-server/lib/router/utils'
import { tracer, traceFn } from '../../tracer' import { tracer, traceFn } from '../../tracer'
import { spans } from './profiling-plugin'
// @ts-ignore: TODO: remove ignore when webpack 5 is stable // @ts-ignore: TODO: remove ignore when webpack 5 is stable
const { RawSource } = webpack.sources || sources const { RawSource } = webpack.sources || sources
...@@ -28,9 +28,11 @@ export type ClientBuildManifest = Record<string, string[]> ...@@ -28,9 +28,11 @@ export type ClientBuildManifest = Record<string, string[]>
// This function takes the asset map generated in BuildManifestPlugin and creates a // This function takes the asset map generated in BuildManifestPlugin and creates a
// reduced version to send to the client. // reduced version to send to the client.
function generateClientManifest( function generateClientManifest(
compiler: any,
assetMap: BuildManifest, assetMap: BuildManifest,
rewrites: Rewrite[] rewrites: Rewrite[]
): string { ): string {
return tracer.withSpan(spans.get(compiler), () => {
const span = tracer.startSpan('NextJsBuildManifest-generateClientManifest') const span = tracer.startSpan('NextJsBuildManifest-generateClientManifest')
return traceFn(span, () => { return traceFn(span, () => {
const clientManifest: ClientBuildManifest = { const clientManifest: ClientBuildManifest = {
...@@ -61,6 +63,7 @@ function generateClientManifest( ...@@ -61,6 +63,7 @@ function generateClientManifest(
return devalue(clientManifest) return devalue(clientManifest)
}) })
})
} }
function isJsFile(file: string): boolean { function isJsFile(file: string): boolean {
...@@ -100,7 +103,8 @@ export default class BuildManifestPlugin { ...@@ -100,7 +103,8 @@ export default class BuildManifestPlugin {
}) })
} }
createAssets(compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
return tracer.withSpan(spans.get(compiler), () => {
const span = tracer.startSpan('NextJsBuildManifest-createassets') const span = tracer.startSpan('NextJsBuildManifest-createassets')
return traceFn(span, () => { return traceFn(span, () => {
const namedChunks: Map<string, CompilationType.Chunk> = const namedChunks: Map<string, CompilationType.Chunk> =
...@@ -149,7 +153,8 @@ export default class BuildManifestPlugin { ...@@ -149,7 +153,8 @@ export default class BuildManifestPlugin {
) )
for (const entrypoint of compilation.entrypoints.values()) { for (const entrypoint of compilation.entrypoints.values()) {
const isAmpRuntime = entrypoint.name === CLIENT_STATIC_FILES_RUNTIME_AMP const isAmpRuntime =
entrypoint.name === CLIENT_STATIC_FILES_RUNTIME_AMP
if (isAmpRuntime) { if (isAmpRuntime) {
for (const file of entrypoint.getFiles()) { for (const file of entrypoint.getFiles()) {
...@@ -202,12 +207,15 @@ export default class BuildManifestPlugin { ...@@ -202,12 +207,15 @@ export default class BuildManifestPlugin {
// eslint-disable-next-line // eslint-disable-next-line
.reduce((a, c) => ((a[c] = assetMap.pages[c]), a), {} as any) .reduce((a, c) => ((a[c] = assetMap.pages[c]), a), {} as any)
assets[BUILD_MANIFEST] = new RawSource(JSON.stringify(assetMap, null, 2)) assets[BUILD_MANIFEST] = new RawSource(
JSON.stringify(assetMap, null, 2)
)
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js` const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
assets[clientManifestPath] = new RawSource( assets[clientManifestPath] = new RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest( `self.__BUILD_MANIFEST = ${generateClientManifest(
compiler,
assetMap, assetMap,
this.rewrites this.rewrites
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()` )};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
...@@ -215,6 +223,7 @@ export default class BuildManifestPlugin { ...@@ -215,6 +223,7 @@ export default class BuildManifestPlugin {
return assets return assets
}) })
})
} }
apply(compiler: Compiler) { apply(compiler: Compiler) {
...@@ -228,7 +237,7 @@ export default class BuildManifestPlugin { ...@@ -228,7 +237,7 @@ export default class BuildManifestPlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, },
(assets: any) => { (assets: any) => {
this.createAssets(compilation, assets) this.createAssets(compiler, compilation, assets)
} }
) )
}) })
...@@ -236,7 +245,7 @@ export default class BuildManifestPlugin { ...@@ -236,7 +245,7 @@ export default class BuildManifestPlugin {
} }
compiler.hooks.emit.tap('NextJsBuildManifest', (compilation: any) => { compiler.hooks.emit.tap('NextJsBuildManifest', (compilation: any) => {
this.createAssets(compilation, compilation.assets) this.createAssets(compiler, compilation, compilation.assets)
}) })
} }
} }
...@@ -4,6 +4,7 @@ import postcss, { Parser } from 'postcss' ...@@ -4,6 +4,7 @@ import postcss, { Parser } from 'postcss'
import webpack from 'webpack' import webpack from 'webpack'
import sources from 'webpack-sources' import sources from 'webpack-sources'
import { tracer, traceAsyncFn } from '../../tracer' import { tracer, traceAsyncFn } from '../../tracer'
import { spans } from './profiling-plugin'
// @ts-ignore: TODO: remove ignore when webpack 5 is stable // @ts-ignore: TODO: remove ignore when webpack 5 is stable
const { RawSource, SourceMapSource } = webpack.sources || sources const { RawSource, SourceMapSource } = webpack.sources || sources
...@@ -71,6 +72,7 @@ export class CssMinimizerPlugin { ...@@ -71,6 +72,7 @@ export class CssMinimizerPlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
}, },
async (assets: any) => { async (assets: any) => {
return tracer.withSpan(spans.get(compiler), () => {
const span = tracer.startSpan('css-minimizer-plugin', { const span = tracer.startSpan('css-minimizer-plugin', {
attributes: { attributes: {
webpackVersion: 5, webpackVersion: 5,
...@@ -111,6 +113,7 @@ export class CssMinimizerPlugin { ...@@ -111,6 +113,7 @@ export class CssMinimizerPlugin {
}) })
) )
}) })
})
} }
) )
return return
...@@ -118,6 +121,7 @@ export class CssMinimizerPlugin { ...@@ -118,6 +121,7 @@ export class CssMinimizerPlugin {
compilation.hooks.optimizeChunkAssets.tapPromise( compilation.hooks.optimizeChunkAssets.tapPromise(
'CssMinimizerPlugin', 'CssMinimizerPlugin',
(chunks: webpack.compilation.Chunk[]) => { (chunks: webpack.compilation.Chunk[]) => {
return tracer.withSpan(spans.get(compiler), () => {
const span = tracer.startSpan('css-minimizer-plugin', { const span = tracer.startSpan('css-minimizer-plugin', {
attributes: { attributes: {
webpackVersion: 4, webpackVersion: 4,
...@@ -153,6 +157,7 @@ export class CssMinimizerPlugin { ...@@ -153,6 +157,7 @@ export class CssMinimizerPlugin {
) )
return res return res
}) })
})
} }
) )
}) })
......
// Copy of https://github.com/webpack/webpack/blob/master/lib/debug/ProfilingPlugin.js import { tracer } from '../../tracer'
// 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' const pluginName = 'ProfilingPlugin'
export class ProfilingPlugin { export const spans = new WeakMap()
tracer: any
/**
* @param {ProfilingPluginOptions=} opts options object
*/
constructor(opts: { tracer: any }) {
this.tracer = opts.tracer
}
export class ProfilingPlugin {
apply(compiler: any) { apply(compiler: any) {
const tracer = this.tracer // Only enabled when instrumentation is loaded
if (!tracer.getCurrentSpan()) {
// Compiler Hooks return
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 compiler.hooks.compile.tap(pluginName, () => {
;[ const span = tracer.startSpan('webpack-compile', {
{ attributes: { name: compiler.name },
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)
)
}) })
spans.set(compiler, span)
}) })
} compiler.hooks.done.tap(pluginName, () => {
spans.get(compiler).end()
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) => {
interceptAllHooksFor(parser, tracer, 'Parser')
}) })
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)
}) })
}
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 */
/** compilation.hooks.normalModuleLoader.tap(
* @param {string} hookName Name of the hook to profile. pluginName,
* @param {Trace} tracer The trace object. (loaderContext: any, module: any) => {
* @param {object} options Options for the profiled fn. const parentSpan = spans.get(module)
* @param {string} options.name Plugin name loaderContext.currentTraceSpan = parentSpan
* @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({ compilation.hooks.succeedModule.tap(pluginName, (module: any) => {
name, spans.get(module).end()
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
} }
} }
...@@ -8,6 +8,7 @@ import jestWorker from 'jest-worker' ...@@ -8,6 +8,7 @@ import jestWorker from 'jest-worker'
import crypto from 'crypto' import crypto from 'crypto'
import cacache from 'next/dist/compiled/cacache' import cacache from 'next/dist/compiled/cacache'
import { tracer, traceAsyncFn } from '../../../../tracer' import { tracer, traceAsyncFn } from '../../../../tracer'
import { spans } from '../../profiling-plugin'
const isWebpack5 = parseInt(webpack.version) === 5 const isWebpack5 = parseInt(webpack.version) === 5
...@@ -113,12 +114,16 @@ class TerserPlugin { ...@@ -113,12 +114,16 @@ class TerserPlugin {
} }
async optimize( async optimize(
compiler,
compilation, compilation,
assets, assets,
optimizeOptions, optimizeOptions,
cache, cache,
{ SourceMapSource, RawSource } { SourceMapSource, RawSource }
) { ) {
const compilerSpan = spans.get(compiler)
return tracer.withSpan(compilerSpan, () => {
const span = tracer.startSpan('terser-webpack-plugin-optimize', { const span = tracer.startSpan('terser-webpack-plugin-optimize', {
attributes: { attributes: {
webpackVersion: isWebpack5 ? 5 : 4, webpackVersion: isWebpack5 ? 5 : 4,
...@@ -304,6 +309,7 @@ class TerserPlugin { ...@@ -304,6 +309,7 @@ class TerserPlugin {
await initializedWorker.end() await initializedWorker.end()
} }
}) })
})
} }
/** /**
...@@ -355,6 +361,7 @@ class TerserPlugin { ...@@ -355,6 +361,7 @@ class TerserPlugin {
}, },
(assets) => (assets) =>
this.optimize( this.optimize(
compiler,
compilation, compilation,
assets, assets,
{ {
...@@ -387,6 +394,7 @@ class TerserPlugin { ...@@ -387,6 +394,7 @@ class TerserPlugin {
pluginName, pluginName,
async (assets) => { async (assets) => {
return await this.optimize( return await this.optimize(
compiler,
compilation, compilation,
assets, assets,
{ {
......
...@@ -46,6 +46,8 @@ import { PrerenderManifest } from '../build' ...@@ -46,6 +46,8 @@ import { PrerenderManifest } from '../build'
import exportPage from './worker' import exportPage from './worker'
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { getPagePath } from '../next-server/server/require' import { getPagePath } from '../next-server/server/require'
import { tracer, traceFn, traceAsyncFn } from '../build/tracer'
import opentelemetryApi from '@opentelemetry/api'
const exists = promisify(existsOrig) const exists = promisify(existsOrig)
...@@ -135,12 +137,20 @@ export default async function exportApp( ...@@ -135,12 +137,20 @@ export default async function exportApp(
options: ExportOptions, options: ExportOptions,
configuration?: NextConfig configuration?: NextConfig
): Promise<void> { ): Promise<void> {
const nextExportSpan = tracer.startSpan('next-export')
return traceAsyncFn(nextExportSpan, async () => {
dir = resolve(dir) dir = resolve(dir)
// attempt to load global env values so they are available in next.config.js // attempt to load global env values so they are available in next.config.js
traceFn(tracer.startSpan('load-dotenv'), () =>
loadEnvConfig(dir, false, Log) loadEnvConfig(dir, false, Log)
)
const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir) const nextConfig =
configuration ||
traceFn(tracer.startSpan('load-next-config'), () =>
loadConfig(PHASE_EXPORT, dir)
)
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)
...@@ -260,7 +270,9 @@ export default async function exportApp( ...@@ -260,7 +270,9 @@ export default async function exportApp(
if (!options.silent) { if (!options.silent) {
Log.info('Copying "static" directory') Log.info('Copying "static" directory')
} }
await recursiveCopy(join(dir, 'static'), join(outDir, 'static')) await traceAsyncFn(tracer.startSpan('copy-static-directory'), () =>
recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
)
} }
// Copy .next/static directory // Copy .next/static directory
...@@ -271,10 +283,12 @@ export default async function exportApp( ...@@ -271,10 +283,12 @@ export default async function exportApp(
if (!options.silent) { if (!options.silent) {
Log.info('Copying "static build" directory') Log.info('Copying "static build" directory')
} }
await recursiveCopy( await traceAsyncFn(tracer.startSpan('copy-next-static-directory'), () =>
recursiveCopy(
join(distDir, CLIENT_STATIC_FILES_PATH), join(distDir, CLIENT_STATIC_FILES_PATH),
join(outDir, '_next', CLIENT_STATIC_FILES_PATH) join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
) )
)
} }
// Get the exportPathMap from the config file // Get the exportPathMap from the config file
...@@ -300,26 +314,27 @@ export default async function exportApp( ...@@ -300,26 +314,27 @@ export default async function exportApp(
) )
} }
const { isNextImageImported } = await promises if (!options.buildExport) {
const { isNextImageImported } = await traceAsyncFn(
tracer.startSpan('is-next-image-imported'),
() =>
promises
.readFile(join(distDir, EXPORT_MARKER), 'utf8') .readFile(join(distDir, EXPORT_MARKER), 'utf8')
.then((text) => JSON.parse(text)) .then((text) => JSON.parse(text))
.catch(() => ({})) .catch(() => ({}))
)
if ( if (isNextImageImported && loader === 'default' && !hasNextSupport) {
isNextImageImported &&
loader === 'default' &&
!options.buildExport &&
!hasNextSupport
) {
throw new Error( throw new Error(
`Image Optimization using Next.js' default loader is not compatible with \`next export\`. `Image Optimization using Next.js' default loader is not compatible with \`next export\`.
Possible solutions: Possible solutions:
- Use \`next start\`, which starts the Image Optimization API. - Use \`next start\`, which starts the Image Optimization API.
- Use Vercel to deploy, which supports Image Optimization. - Use Vercel to deploy, which supports Image Optimization.
- Configure a third-party loader in \`next.config.js\`. - Configure a third-party loader in \`next.config.js\`.
Read more: https://err.sh/next.js/export-image-api` Read more: https://err.sh/next.js/export-image-api`
) )
} }
}
// Start the rendering process // Start the rendering process
const renderOpts = { const renderOpts = {
...@@ -355,13 +370,17 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -355,13 +370,17 @@ Read more: https://err.sh/next.js/export-image-api`
if (!options.silent && !options.buildExport) { if (!options.silent && !options.buildExport) {
Log.info(`Launching ${threads} workers`) Log.info(`Launching ${threads} workers`)
} }
const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, { const exportPathMap = await traceAsyncFn(
tracer.startSpan('run-export-path-map'),
() =>
nextConfig.exportPathMap(defaultPathMap, {
dev: false, dev: false,
dir, dir,
outDir, outDir,
distDir, distDir,
buildId, buildId,
}) })
)
if (!exportPathMap['/404'] && !exportPathMap['/404.html']) { if (!exportPathMap['/404'] && !exportPathMap['/404.html']) {
exportPathMap['/404'] = exportPathMap['/404.html'] = { exportPathMap['/404'] = exportPathMap['/404.html'] = {
...@@ -454,18 +473,20 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -454,18 +473,20 @@ Read more: https://err.sh/next.js/export-image-api`
if (!options.silent) { if (!options.silent) {
Log.info('Copying "public" directory') Log.info('Copying "public" directory')
} }
await recursiveCopy(publicDir, outDir, { await traceAsyncFn(tracer.startSpan('copy-public-directory'), () =>
recursiveCopy(publicDir, outDir, {
filter(path) { filter(path) {
// Exclude paths used by pages // Exclude paths used by pages
return !exportPathMap[path] return !exportPathMap[path]
}, },
}) })
)
} }
const worker = new Worker(require.resolve('./worker'), { const worker = new Worker(require.resolve('./worker'), {
maxRetries: 0, maxRetries: 0,
numWorkers: threads, numWorkers: threads,
enableWorkerThreads: nextConfig.experimental.workerThreads, enableWorkerThreads: true,
exposedMethods: ['default'], exposedMethods: ['default'],
}) as Worker & { default: typeof exportPage } }) as Worker & { default: typeof exportPage }
...@@ -477,6 +498,17 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -477,6 +498,17 @@ Read more: https://err.sh/next.js/export-image-api`
await Promise.all( await Promise.all(
filteredPaths.map(async (path) => { filteredPaths.map(async (path) => {
const pageExportSpan = tracer.startSpan('export-page', {
attributes: { path },
})
return traceAsyncFn(pageExportSpan, async () => {
const spanContext = {}
opentelemetryApi.propagation.inject(
opentelemetryApi.context.active(),
spanContext
)
const result = await worker.default({ const result = await worker.default({
path, path,
pathMap: exportPathMap[path], pathMap: exportPathMap[path],
...@@ -491,6 +523,7 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -491,6 +523,7 @@ Read more: https://err.sh/next.js/export-image-api`
optimizeFonts: nextConfig.experimental.optimizeFonts, optimizeFonts: nextConfig.experimental.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages, optimizeImages: nextConfig.experimental.optimizeImages,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
spanContext,
}) })
for (const validation of result.ampValidations || []) { for (const validation of result.ampValidations || []) {
...@@ -517,6 +550,7 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -517,6 +550,7 @@ Read more: https://err.sh/next.js/export-image-api`
if (progress) progress() if (progress) progress()
}) })
})
) )
worker.end() worker.end()
...@@ -596,4 +630,5 @@ Read more: https://err.sh/next.js/export-image-api` ...@@ -596,4 +630,5 @@ Read more: https://err.sh/next.js/export-image-api`
if (telemetry) { if (telemetry) {
await telemetry.flush() await telemetry.flush()
} }
})
} }
...@@ -16,6 +16,8 @@ import { GetStaticProps } from '../types' ...@@ -16,6 +16,8 @@ import { GetStaticProps } from '../types'
import { requireFontManifest } from '../next-server/server/require' import { requireFontManifest } from '../next-server/server/require'
import { FontManifest } from '../next-server/server/font-utils' import { FontManifest } from '../next-server/server/font-utils'
import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
import { tracer, traceAsyncFn } from '../build/tracer'
import opentelemetryApi from '@opentelemetry/api'
const envConfig = require('../next-server/lib/runtime-config') const envConfig = require('../next-server/lib/runtime-config')
...@@ -50,6 +52,7 @@ interface ExportPageInput { ...@@ -50,6 +52,7 @@ interface ExportPageInput {
optimizeFonts: boolean optimizeFonts: boolean
optimizeImages: boolean optimizeImages: boolean
optimizeCss: any optimizeCss: any
spanContext: any
} }
interface ExportPageResults { interface ExportPageResults {
...@@ -82,6 +85,7 @@ type ComponentModule = ComponentType<{}> & { ...@@ -82,6 +85,7 @@ type ComponentModule = ComponentType<{}> & {
} }
export default async function exportPage({ export default async function exportPage({
spanContext,
path, path,
pathMap, pathMap,
distDir, distDir,
...@@ -96,6 +100,13 @@ export default async function exportPage({ ...@@ -96,6 +100,13 @@ export default async function exportPage({
optimizeImages, optimizeImages,
optimizeCss, optimizeCss,
}: ExportPageInput): Promise<ExportPageResults> { }: ExportPageInput): Promise<ExportPageResults> {
return opentelemetryApi.context.with(
opentelemetryApi.propagation.extract(
opentelemetryApi.context.active(),
spanContext
),
() => {
return traceAsyncFn(tracer.startSpan('export-page-worker'), async () => {
let results: ExportPageResults = { let results: ExportPageResults = {
ampValidations: [], ampValidations: [],
} }
...@@ -116,7 +127,10 @@ export default async function exportPage({ ...@@ -116,7 +127,10 @@ export default async function exportPage({
delete query.__nextSsgPath delete query.__nextSsgPath
if (renderOpts.locale) { if (renderOpts.locale) {
const localePathResult = normalizeLocalePath(path, renderOpts.locales) const localePathResult = normalizeLocalePath(
path,
renderOpts.locales
)
if (localePathResult.detectedLocale) { if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname updatedPath = localePathResult.pathname
...@@ -141,7 +155,8 @@ export default async function exportPage({ ...@@ -141,7 +155,8 @@ export default async function exportPage({
// Check if the page is a specified dynamic route // Check if the page is a specified dynamic route
if (isDynamic && page !== path) { if (isDynamic && page !== path) {
params = getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined params =
getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined
if (params) { if (params) {
// we have to pass these separately for serverless // we have to pass these separately for serverless
if (!serverless) { if (!serverless) {
...@@ -221,7 +236,9 @@ export default async function exportPage({ ...@@ -221,7 +236,9 @@ export default async function exportPage({
) )
if (getServerSideProps) { if (getServerSideProps) {
throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`) throw new Error(
`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`
)
} }
// if it was auto-exported the HTML is loaded here // if it was auto-exported the HTML is loaded here
...@@ -276,7 +293,9 @@ export default async function exportPage({ ...@@ -276,7 +293,9 @@ export default async function exportPage({
const components = await loadComponents(distDir, page, serverless) const components = await loadComponents(distDir, page, serverless)
if (components.getServerSideProps) { if (components.getServerSideProps) {
throw new Error(`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`) throw new Error(
`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`
)
} }
// for non-dynamic SSG pages we should have already // for non-dynamic SSG pages we should have already
...@@ -436,4 +455,7 @@ export default async function exportPage({ ...@@ -436,4 +455,7 @@ export default async function exportPage({
) )
return { ...results, error: true } return { ...results, error: 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