-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtrace-file-utils.ts
More file actions
268 lines (252 loc) · 6.84 KB
/
trace-file-utils.ts
File metadata and controls
268 lines (252 loc) · 6.84 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
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
import os from 'node:os';
import type { PerformanceMark, PerformanceMeasure } from 'node:perf_hooks';
import { threadId } from 'node:worker_threads';
import { defaultClock } from './clock-epoch.js';
import type {
BeginEvent,
CompleteEvent,
EndEvent,
InstantEvent,
InstantEventArgs,
InstantEventTracingStartedInBrowser,
SpanEvent,
SpanEventArgs,
TraceEvent,
TraceEventContainer,
} from './trace-file.type.js';
/** Global counter for generating unique span IDs within a trace */
// eslint-disable-next-line functional/no-let
let id2Count = 0;
/**
* Generates a unique ID for linking begin and end span events in Chrome traces.
* @returns Object with local ID string for the id2 field
*/
export const nextId2 = () => ({ local: `0x${++id2Count}` });
/**
* Provides default values for trace event properties.
* @param opt - Optional overrides for pid, tid, and timestamp
* @returns Object with pid, tid, and timestamp
*/
const defaults = (opt?: { pid?: number; tid?: number; ts?: number }) => ({
pid: opt?.pid ?? process.pid,
tid: opt?.tid ?? threadId,
ts: opt?.ts ?? defaultClock.epochNowUs(),
});
/**
* Generates a unique frame tree node ID from process and thread IDs.
* @param pid - Process ID
* @param tid - Thread ID
* @returns Combined numeric ID
*/
export const frameTreeNodeId = (pid: number, tid: number) =>
Number.parseInt(`${pid}0${tid}`, 10);
/**
* Generates a frame name string from process and thread IDs.
* @param pid - Process ID
* @param tid - Thread ID
* @returns Formatted frame name
*/
export const frameName = (pid: number, tid: number) => `FRAME0P${pid}T${tid}`;
/**
* Creates an instant trace event for marking a point in time.
* @param opt - Event configuration options
* @returns InstantEvent object
*/
export const getInstantEvent = (opt: {
name: string;
ts?: number;
pid?: number;
tid?: number;
args?: InstantEventArgs;
}): InstantEvent => ({
cat: 'blink.user_timing',
ph: 'i',
name: opt.name,
...defaults(opt),
args: opt.args ?? {},
});
/**
* Creates a start tracing event with frame information.
* This event is needed at the beginning of the traceEvents array to make tell the UI profiling has started, and it should visualize the data.
* @param opt - Tracing configuration options
* @returns StartTracingEvent object
*/
export const getInstantEventTracingStartedInBrowser = (opt: {
url: string;
ts?: number;
pid?: number;
tid?: number;
}): InstantEventTracingStartedInBrowser => {
const { pid, tid, ts } = defaults(opt);
const id = frameTreeNodeId(pid, tid);
return {
cat: 'devtools.timeline',
ph: 'i',
name: 'TracingStartedInBrowser',
pid,
tid,
ts,
args: {
data: {
frameTreeNodeId: id,
frames: [
{
frame: frameName(pid, tid),
isInPrimaryMainFrame: true,
isOutermostMainFrame: true,
name: '',
processId: pid,
url: opt.url,
},
],
persistentIds: true,
},
},
};
};
/**
* Creates a complete trace event with duration.
* @param opt - Event configuration with name and duration
* @returns CompleteEvent object
*/
export const getCompleteEvent = (opt: {
name: string;
dur: number;
ts?: number;
pid?: number;
tid?: number;
}): CompleteEvent => ({
cat: 'devtools.timeline',
ph: 'X',
name: opt.name,
dur: opt.dur,
...defaults(opt),
args: {},
});
/** Options for creating span events */
type SpanOpt = {
name: string;
id2: { local: string };
ts?: number;
pid?: number;
tid?: number;
args?: SpanEventArgs;
};
/**
* Creates a begin span event.
* @param ph - Phase ('b' for begin)
* @param opt - Span event options
* @returns BeginEvent object
*/
export function getSpanEvent(ph: 'b', opt: SpanOpt): BeginEvent;
/**
* Creates an end span event.
* @param ph - Phase ('e' for end)
* @param opt - Span event options
* @returns EndEvent object
*/
export function getSpanEvent(ph: 'e', opt: SpanOpt): EndEvent;
/**
* Creates a span event (begin or end).
* @param ph - Phase ('b' or 'e')
* @param opt - Span event options
* @returns SpanEvent object
*/
export function getSpanEvent(ph: 'b' | 'e', opt: SpanOpt): SpanEvent {
return {
cat: 'blink.user_timing',
ph,
name: opt.name,
id2: opt.id2,
...defaults(opt),
args: opt.args?.data?.detail
? { data: { detail: opt.args.data.detail } }
: {},
};
}
/**
* Creates a pair of begin and end span events.
* @param opt - Span configuration with start/end timestamps
* @returns Tuple of BeginEvent and EndEvent
*/
export const getSpan = (opt: {
name: string;
tsB: number;
tsE: number;
id2?: { local: string };
pid?: number;
tid?: number;
args?: SpanEventArgs;
tsMarkerPadding?: number;
}): [BeginEvent, EndEvent] => {
// tsMarkerPadding is here to make the measure slightly smaller so the markers align perfectly.
// Otherwise, the marker is visible at the start of the measure below the frame
// No padding Padding
// spans: ======== |======|
// marks: | |
const pad = opt.tsMarkerPadding ?? 1;
// b|e need to share the same id2
const id2 = opt.id2 ?? nextId2();
return [
getSpanEvent('b', {
...opt,
id2,
ts: opt.tsB + pad,
}),
getSpanEvent('e', {
...opt,
id2,
ts: opt.tsE - pad,
}),
];
};
/**
* Converts a PerformanceMark to an instant trace event.
* @param entry - Performance mark entry
* @param opt - Optional overrides for name, pid, and tid
* @returns InstantEvent object
*/
export const markToInstantEvent = (
entry: PerformanceMark,
opt?: { name?: string; pid?: number; tid?: number },
): InstantEvent =>
getInstantEvent({
...opt,
name: opt?.name ?? entry.name,
ts: defaultClock.fromEntry(entry),
args: entry.detail ? { detail: entry.detail } : undefined,
});
/**
* Converts a PerformanceMeasure to a pair of span events.
* @param entry - Performance measure entry
* @param opt - Optional overrides for name, pid, and tid
* @returns Tuple of BeginEvent and EndEvent
*/
export const measureToSpanEvents = (
entry: PerformanceMeasure,
opt?: { name?: string; pid?: number; tid?: number },
): [BeginEvent, EndEvent] =>
getSpan({
...opt,
name: opt?.name ?? entry.name,
tsB: defaultClock.fromEntry(entry),
tsE: defaultClock.fromEntry(entry, true),
args: entry.detail ? { data: { detail: entry.detail } } : undefined,
});
/**
* Creates a complete trace file container with metadata.
* @param opt - Trace file configuration
* @returns TraceEventContainer with events and metadata
*/
export const getTraceFile = (opt: {
traceEvents: TraceEvent[];
startTime?: string;
}): TraceEventContainer => ({
traceEvents: opt.traceEvents,
displayTimeUnit: 'ms',
metadata: {
source: 'Node.js UserTiming',
startTime: opt.startTime ?? new Date().toISOString(),
hardwareConcurrency: os.cpus().length,
},
});