feat: timing plugin and Server-Timing

This commit is contained in:
Pooya Parsa 2020-11-15 01:52:18 +01:00
parent 5bd6531f5d
commit 740bf073b2
3 changed files with 37 additions and 6 deletions

View File

@ -37,7 +37,7 @@ export interface SLSOptions {
minify: boolean
externals: boolean
rollupConfig?: any
logStartup: boolean
timing: boolean
inlineChunks: boolean
renderer: string
analyze: boolean
@ -72,7 +72,7 @@ export function getoptions (nuxtOptions: Nuxt['options'], serverless: SLSConfig)
staticAssets: nuxtOptions.generate.staticAssets,
outName: '_nuxt.js',
logStartup: true,
timing: true,
inlineChunks: true,
minify: false,
externals: false,

View File

@ -14,8 +14,10 @@ import analyze from 'rollup-plugin-analyzer'
import hasha from 'hasha'
import { SLSOptions } from '../config'
import { resolvePath, MODULE_DIR } from '../utils'
import { dynamicRequire } from './dynamic-require'
import { externals } from './externals'
import { timing } from './timing'
const mapArrToVal = (val, arr) => arr.reduce((p, c) => ({ ...p, [c]: val }), {})
@ -107,10 +109,8 @@ export const getRollupConfig = (options: SLSOptions) => {
plugins: []
}
if (options.logStartup) {
rollupConfig.output.intro += 'global._startTime = global.process.hrtime();'
// eslint-disable-next-line no-template-curly-in-string
rollupConfig.output.outro += 'global._endTime = global.process.hrtime(global._startTime); global._coldstart = ((global._endTime[0] * 1e9) + global._endTime[1]) / 1e6; console.log(`λ Cold start took: ${global._coldstart}ms (${typeof __filename !== "undefined" ? __filename.replace(process.cwd(), "") : "<entry>"})`);'
if (options.timing) {
rollupConfig.plugins.push(timing())
}
// https://github.com/rollup/plugins/tree/master/packages/replace

View File

@ -0,0 +1,31 @@
import { extname } from 'path'
import type { Plugin, RenderedChunk } from 'rollup'
export interface Options { }
const TIMING = 'global.__timing__'
const iife = code => `(function() { ${code.trim()} })();`.replace(/\n/g, '')
const HELPER = TIMING + '=' + iife(`
const hrtime = global.process.hrtime;
const start = () => hrtime();
const end = s => { const d = hrtime(s); return ((d[0] * 1e9) + d[1]) / 1e6; };
const _s = {};
const metrics = [];
const logStart = id => { _s[id] = hrtime(); };
const logEnd = id => { const t = end(_s[id]); delete _s[id]; metrics.push([id, t]); console.log('◈', id, t, 'ms'); };
return { hrtime, start, end, metrics, logStart, logEnd };
`)
export function timing (_opts: Options = {}): Plugin {
return {
name: 'timing',
renderChunk (code, chunk: RenderedChunk) {
let name = chunk.fileName || ''
name = name.replace(extname(name), '')
return "'use strict';" + HELPER + `${TIMING}.logStart('import:${name}');` + code + `;${TIMING}.logEnd('import:${name}');`
}
}
}