-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathperformance.ts
296 lines (255 loc) · 10.1 KB
/
performance.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import {performance, PerformanceObserver} from 'node:perf_hooks'
import {makeDebug} from './logger'
import {settings} from './settings'
type Details = Record<string, boolean | number | string | string[]>
type PerfResult = {
details: Details
duration: number
method: string | undefined
module: string
name: string
scope: string | undefined
}
type PerfHighlights = {
hookRunTimes: Record<string, Record<string, number>>
'oclif.commandLoadMs': number
'oclif.commandRunMs': number
'oclif.configLoadMs': number
'oclif.corePluginsLoadMs': number
'oclif.initHookMs': number
'oclif.initMs': number
'oclif.linkedPluginsLoadMs': number
'oclif.postrunHookMs': number
'oclif.prerunHookMs': number
'oclif.runMs': number
'oclif.userPluginsLoadMs': number
pluginLoadTimes: Record<string, {details: Details; duration: number}>
}
export const OCLIF_MARKER_OWNER = '@oclif/core'
class Marker {
public method: string
public module: string
public scope: string
public stopped = false
private startMarker: string
private stopMarker: string
constructor(
public owner: string,
public name: string,
public details: Details = {},
) {
this.startMarker = `${this.name}-start`
this.stopMarker = `${this.name}-stop`
const [caller, scope] = name.split('#')
const [module, method] = caller.split('.')
this.module = module
this.method = method
this.scope = scope
performance.mark(this.startMarker)
}
public addDetails(details: Details): void {
this.details = {...this.details, ...details}
}
public measure() {
performance.measure(this.name, this.startMarker, this.stopMarker)
}
public stop() {
this.stopped = true
performance.mark(this.stopMarker)
}
}
export class Performance {
private static _oclifPerf: PerfHighlights
/* Key: marker.owner */
private static _results = new Map<string, PerfResult[]>()
/* Key: marker.name */
private static markers = new Map<string, Marker>()
/**
* Collect performance results into static Performance.results
*
* @returns Promise<void>
*/
public static async collect(): Promise<void> {
if (!Performance.enabled) return
if (Performance._results.size > 0) return
const markers = [...Performance.markers.values()]
if (markers.length === 0) return
for (const marker of markers.filter((m) => !m.stopped)) {
marker.stop()
}
return new Promise((resolve) => {
// eslint-disable-next-line complexity
const perfObserver = new PerformanceObserver((items) => {
for (const entry of items.getEntries()) {
const marker = Performance.markers.get(entry.name)
if (marker) {
const result = {
details: marker.details,
duration: entry.duration,
method: marker.method,
module: marker.module,
name: entry.name,
scope: marker.scope,
}
const existing = Performance._results.get(marker.owner) ?? []
Performance._results.set(marker.owner, [...existing, result])
}
}
const oclifResults = Performance._results.get(OCLIF_MARKER_OWNER) ?? []
const command = oclifResults.find((r) => r.name.startsWith('config.runCommand'))
const commandLoadTime = command
? (Performance.getResult(
OCLIF_MARKER_OWNER,
`plugin.findCommand#${command.details.plugin}.${command.details.command}`,
)?.duration ?? 0)
: 0
const pluginLoadTimes = Object.fromEntries(
oclifResults
.filter(({name}) => name.startsWith('plugin.load#'))
.sort((a, b) => b.duration - a.duration)
.map(({details, duration, scope}) => [scope, {details, duration}]),
)
const hookRunTimes = oclifResults
.filter(({name}) => name.startsWith('config.runHook#'))
.reduce(
(acc, perfResult) => {
const event = perfResult.details.event as string
if (event) {
if (!acc[event]) acc[event] = {}
acc[event][perfResult.scope!] = perfResult.duration
} else {
const event = perfResult.scope!
if (!acc[event]) acc[event] = {}
acc[event].total = perfResult.duration
}
return acc
},
{} as Record<string, Record<string, number>>,
)
const pluginLoadTimeByType = Object.fromEntries(
oclifResults
.filter(({name}) => name.startsWith('config.loadPlugins#'))
.sort((a, b) => b.duration - a.duration)
.map(({duration, scope}) => [scope, duration]),
)
Performance._oclifPerf = {
hookRunTimes,
'oclif.commandLoadMs': commandLoadTime,
'oclif.commandRunMs': oclifResults.find(({name}) => name.startsWith('config.runCommand#'))?.duration ?? 0,
'oclif.configLoadMs': Performance.getResult(OCLIF_MARKER_OWNER, 'config.load')?.duration ?? 0,
'oclif.corePluginsLoadMs': pluginLoadTimeByType.core ?? 0,
'oclif.initHookMs': hookRunTimes.init?.total ?? 0,
'oclif.initMs': Performance.getResult(OCLIF_MARKER_OWNER, 'main.run#init')?.duration ?? 0,
'oclif.linkedPluginsLoadMs': pluginLoadTimeByType.link ?? 0,
'oclif.postrunHookMs': hookRunTimes.postrun?.total ?? 0,
'oclif.prerunHookMs': hookRunTimes.prerun?.total ?? 0,
'oclif.runMs': Performance.getResult(OCLIF_MARKER_OWNER, 'main.run')?.duration ?? 0,
'oclif.userPluginsLoadMs': pluginLoadTimeByType.user ?? 0,
pluginLoadTimes,
}
resolve()
})
perfObserver.observe({buffered: true, entryTypes: ['measure']})
for (const marker of markers) {
try {
marker.measure()
} catch {
// ignore
}
}
performance.clearMarks()
})
}
/**
* Add debug logs for plugin loading performance
*/
public static debug(): void {
if (!Performance.enabled) return
const oclifDebug = makeDebug('perf')
const processUpTime = (process.uptime() * 1000).toFixed(4)
oclifDebug('Process Uptime: %sms', processUpTime)
oclifDebug('Oclif Time: %sms', Performance.oclifPerf['oclif.runMs'].toFixed(4))
oclifDebug('Init Time: %sms', Performance.oclifPerf['oclif.initMs'].toFixed(4))
oclifDebug('Config Load Time: %sms', Performance.oclifPerf['oclif.configLoadMs'].toFixed(4))
oclifDebug(
' • Root Plugin Load Time: %sms',
Performance.getResult(OCLIF_MARKER_OWNER, 'plugin.load#root')?.duration.toFixed(4) ?? 0,
)
oclifDebug(
' • Plugins Load Time: %sms',
Performance.getResult(OCLIF_MARKER_OWNER, 'config.loadAllPlugins')?.duration.toFixed(4) ?? 0,
)
oclifDebug(
' • Commands Load Time: %sms',
Performance.getResult(OCLIF_MARKER_OWNER, 'config.loadAllCommands')?.duration.toFixed(4) ?? 0,
)
oclifDebug('Core Plugin Load Time: %sms', Performance.oclifPerf['oclif.corePluginsLoadMs'].toFixed(4))
oclifDebug('User Plugin Load Time: %sms', Performance.oclifPerf['oclif.userPluginsLoadMs'].toFixed(4))
oclifDebug('Linked Plugin Load Time: %sms', Performance.oclifPerf['oclif.linkedPluginsLoadMs'].toFixed(4))
oclifDebug('Plugin Load Times:')
for (const [plugin, result] of Object.entries(Performance.oclifPerf.pluginLoadTimes)) {
if (result.details.hasManifest) {
oclifDebug(` ${plugin}: ${result.duration.toFixed(4)}ms`)
} else {
oclifDebug(` ${plugin}: ${result.duration.toFixed(4)}ms (no manifest!)`)
}
}
oclifDebug('Hook Run Times:')
for (const [event, runTimes] of Object.entries(Performance.oclifPerf.hookRunTimes)) {
oclifDebug(` ${event}:`)
for (const [plugin, duration] of Object.entries(runTimes)) {
oclifDebug(` ${plugin}: ${duration.toFixed(4)}ms`)
}
}
oclifDebug('Command Load Time: %sms', Performance.oclifPerf['oclif.commandLoadMs'].toFixed(4))
oclifDebug('Command Run Time: %sms', Performance.oclifPerf['oclif.commandRunMs'].toFixed(4))
if (Performance.oclifPerf['oclif.configLoadMs'] > Performance.oclifPerf['oclif.runMs']) {
oclifDebug(
'! Config load time is greater than total oclif time. This might mean that Config was instantiated before oclif was run.',
)
}
const nonCoreDebug = makeDebug('non-oclif-perf')
const nonCorePerf = Performance.results
if (nonCorePerf.size > 0) {
nonCoreDebug('Non-Core Performance Measurements:')
for (const [owner, results] of nonCorePerf) {
nonCoreDebug(` ${owner}:`)
for (const result of results) {
nonCoreDebug(` ${result.name}: ${result.duration.toFixed(4)}ms`)
}
}
}
}
public static getResult(owner: string, name: string): PerfResult | undefined {
return Performance._results.get(owner)?.find((r) => r.name === name)
}
/**
* Add a new performance marker
*
* @param owner An npm package like `@oclif/core` or `@salesforce/source-tracking`
* @param name Name of the marker. Use `module.method#scope` format
* @param details Arbitrary details to attach to the marker
* @returns Marker instance
*/
public static mark(owner: string, name: string, details: Details = {}): Marker | undefined {
if (!Performance.enabled) return
const marker = new Marker(owner, name, details)
Performance.markers.set(marker.name, marker)
return marker
}
public static get enabled(): boolean {
return settings.performanceEnabled ?? false
}
public static get oclifPerf(): PerfHighlights | Record<string, never> {
if (!Performance.enabled) return {}
if (Performance._oclifPerf) return Performance._oclifPerf
throw new Error('Perf results not available. Did you forget to call await Performance.collect()?')
}
/** returns a map of owner, PerfResult[]. Excludes oclif PerfResult, which you can get from oclifPerf */
public static get results(): Map<string, PerfResult[]> {
if (!Performance.enabled) return new Map()
return new Map<string, PerfResult[]>(
[...Performance._results.entries()].filter(([owner]) => owner !== OCLIF_MARKER_OWNER),
)
}
}