-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathprofiler.ts
More file actions
239 lines (224 loc) · 7.8 KB
/
profiler.ts
File metadata and controls
239 lines (224 loc) · 7.8 KB
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
import process from 'node:process';
import { threadId } from 'node:worker_threads';
import { isEnvVarEnabled } from '../env.js';
import {
type ActionTrackConfigs,
type MeasureCtxOptions,
type MeasureOptions,
asOptions,
markerPayload,
measureCtx,
setupTracks,
} from '../user-timing-extensibility-api-utils.js';
import type {
ActionTrackEntryPayload,
DevToolsColor,
EntryMeta,
} from '../user-timing-extensibility-api.type.js';
import { PROFILER_ENABLED_ENV_VAR } from './constants.js';
/**
* Generates a unique profiler ID based on performance time origin, process ID, thread ID, and instance count.
*/
export function getProfilerId() {
// eslint-disable-next-line functional/immutable-data
return `${Math.round(performance.timeOrigin)}.${process.pid}.${threadId}.${++Profiler.instanceCount}`;
}
/**
* Configuration options for creating a Profiler instance.
*
* @template T - Record type defining available track names and their configurations
*/
type ProfilerMeasureOptions<T extends ActionTrackConfigs> =
MeasureCtxOptions & {
/** Custom track configurations that will be merged with default settings */
tracks?: Record<keyof T, Partial<ActionTrackEntryPayload>>;
/** Whether profiling should be enabled (defaults to CP_PROFILING env var) */
enabled?: boolean;
};
/**
* Options for creating a performance marker.
*/
export type MarkerOptions = EntryMeta & { color?: DevToolsColor };
/**
* Options for configuring a Profiler instance.
*
* This is an alias for ProfilerMeasureOptions for backward compatibility.
*
* @template T - Record type defining available track names and their configurations
*
* @property enabled - Whether profiling is enabled (defaults to CP_PROFILING env var)
* @property prefix - Prefix for all measurement names
* @property track - Default track name for measurements
* @property trackGroup - Default track group for organization
* @property color - Default color for track entries
* @property tracks - Custom track configurations merged with defaults
*/
export type ProfilerOptions<T extends ActionTrackConfigs = ActionTrackConfigs> =
ProfilerMeasureOptions<T>;
/**
* Performance profiler that creates structured timing measurements with Chrome DevTools Extensibility API payloads.
*
* This class provides high-level APIs for performance monitoring focused on Chrome DevTools Extensibility API data.
* It supports both synchronous and asynchronous operations with all having smart defaults for custom track data.
*
*/
export class Profiler<T extends ActionTrackConfigs> {
static instanceCount = 0;
readonly id = getProfilerId();
#enabled: boolean;
readonly #defaults: ActionTrackEntryPayload;
readonly tracks: Record<keyof T, ActionTrackEntryPayload> | undefined;
readonly #ctxOf: ReturnType<typeof measureCtx>;
/**
* Creates a new Profiler instance with the specified configuration.
*
* @param options - Configuration options for the profiler
* @param options.tracks - Custom track configurations merged with defaults
* @param options.prefix - Prefix for all measurement names
* @param options.track - Default track name for measurements
* @param options.trackGroup - Default track group for organization
* @param options.color - Default color for track entries
* @param options.enabled - Whether profiling is enabled (defaults to CP_PROFILING env var)
*
*/
constructor(options: ProfilerOptions<T>) {
const { tracks, prefix, enabled, ...defaults } = options;
const dataType = 'track-entry';
this.#enabled = enabled ?? isEnvVarEnabled(PROFILER_ENABLED_ENV_VAR);
this.#defaults = { ...defaults, dataType };
this.tracks = tracks
? setupTracks({ ...defaults, dataType }, tracks)
: undefined;
this.#ctxOf = measureCtx({
...defaults,
dataType,
prefix,
});
}
/**
* Sets enabled state for this profiler.
*
* Also sets the `CP_PROFILING` environment variable.
* This means any future {@link Profiler} instantiations (including child processes) will use the same enabled state.
*
* @param enabled - Whether profiling should be enabled
*/
setEnabled(enabled: boolean): void {
process.env[PROFILER_ENABLED_ENV_VAR] = `${enabled}`;
this.#enabled = enabled;
}
/**
* Is profiling enabled?
*
* Profiling is enabled by {@link setEnabled} call or `CP_PROFILING` environment variable.
*
* @returns Whether profiling is currently enabled
*/
isEnabled(): boolean {
return this.#enabled;
}
/**
* Creates a performance mark including payload for a Chrome DevTools 'marker' item.
*
* Markers appear as vertical lines spanning all tracks and can include custom metadata
* for debugging and performance analysis. When profiling is disabled, this method
* returns immediately without creating any performance entries.
*
* @param name - Unique name for the marker
* @param opt - Metadata and styling for the marker
* @param opt.color - Color of the marker line (defaults to profiler default)
* @param opt.tooltipText - Text shown on hover
* @param opt.properties - Key-value pairs for detailed view show on click
*
* @example
* profiler.marker('user-action-start', {
* color: 'primary',
* tooltipText: 'User clicked save button',
* properties: [
* ['action', 'save'],
* ['elementId', 'save-btn']
* ]
* });
*/
marker(name: string, opt?: MarkerOptions): void {
if (!this.#enabled) {
return;
}
performance.mark(
name,
asOptions(
markerPayload({
// marker only takes default color, no TrackMeta
...(this.#defaults.color ? { color: this.#defaults.color } : {}),
...opt,
}),
),
);
}
/**
* Measures the execution time of a synchronous operation.
*
* For asynchronous operations, use the {@link measureAsync} method.
*
* Creates performance start/end marks and a final measure.
* All entries have Chrome DevTools Extensibility API payload and are visualized under custom tracks.
* When profiling is disabled, executes the work function directly without overhead.
*
* @template R - The return type of the work function
* @param event - Name for this measurement event
* @param work - Function to execute and measure
* @param options - Measurement configuration overrides
* @returns The result of the work function
*
*/
measure<R>(event: string, work: () => R, options?: MeasureOptions<R>): R {
if (!this.#enabled) {
return work();
}
const { start, success, error } = this.#ctxOf(event, options);
start();
try {
const r = work();
success(r);
return r;
} catch (error_) {
error(error_);
throw error_;
}
}
/**
* Measures the execution time of an asynchronous operation.
*
* For synchronous operations, use the {@link measure} method.
*
* Creates performance start/end marks and a final measure.
* All entries have Chrome DevTools Extensibility API payload and are visualized under custom tracks.
* When profiling is disabled, executes and awaits the work function directly without overhead.
*
* @template R - The resolved type of the work promise
* @param event - Name for this measurement event
* @param work - Function returning a promise to execute and measure
* @param options - Measurement configuration overrides
* @returns Promise that resolves to the result of the work function
*
*/
async measureAsync<R>(
event: string,
work: () => Promise<R>,
options?: MeasureOptions<R>,
): Promise<R> {
if (!this.#enabled) {
return await work();
}
const { start, success, error } = this.#ctxOf(event, options);
start();
try {
const r = await work();
success(r);
return r;
} catch (error_) {
error(error_);
throw error_;
}
}
}