-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtrace-file-utils.ts
More file actions
432 lines (406 loc) · 12.1 KB
/
Copy pathtrace-file-utils.ts
File metadata and controls
432 lines (406 loc) · 12.1 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import type {
PerformanceEntry,
PerformanceMark,
PerformanceMeasure,
} from 'node:perf_hooks';
import { threadId } from 'node:worker_threads';
import { defaultClock } from '../clock-epoch.js';
import type { UserTimingDetail } from '../user-timing-extensibility-api.type.js';
import type {
BeginEvent,
CompleteEvent,
EndEvent,
InstantEvent,
InstantEventArgs,
InstantEventTracingStartedInBrowser,
SpanEvent,
SpanEventArgs,
TraceEvent,
TraceEventContainer,
TraceEventRaw,
TraceMetadata,
UserTimingTraceEvent,
} 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 process ID, thread ID, and timestamp
* @param opt.pid - Process ID override, defaults to current process PID
* @param opt.tid - Thread ID override, defaults to current thread ID
* @param opt.ts - Timestamp override in microseconds, defaults to current epoch time
* @returns Object containing pid, tid, and ts with defaults applied
*/
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,
});
/**
* Converts a PerformanceEntry to an array of UserTimingTraceEvents.
* A mark is converted to an instant event, and a measure is converted to a pair of span events.
* Other entry types are ignored.
* @param entry - Performance entry
* @returns UserTimingTraceEvent[]
*/
export function entryToTraceEvents(
entry: PerformanceEntry,
): UserTimingTraceEvent[] {
if (entry.entryType === 'mark') {
return [markToInstantEvent(entry as PerformanceMark)];
}
if (entry.entryType === 'measure') {
return measureToSpanEvents(entry as PerformanceMeasure);
}
return [];
}
/**
* Creates trace metadata object with standard DevTools fields and custom metadata.
* @param startDate - Optional start date for the trace, defaults to current date
* @param metadata - Optional additional metadata to merge into the trace metadata
* @returns TraceMetadata object with source, startTime, and merged custom metadata
*/
export function getTraceMetadata(
startDate?: Date,
metadata?: Record<string, unknown>,
) {
return {
source: 'DevTools',
startTime: startDate?.toISOString() ?? new Date().toISOString(),
hardwareConcurrency: 1,
dataOrigin: 'TraceEvents',
...metadata,
};
}
/**
* 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;
metadata?: Partial<TraceMetadata>;
}): TraceEventContainer => ({
traceEvents: opt.traceEvents,
displayTimeUnit: 'ms',
metadata: getTraceMetadata(
opt.startTime ? new Date(opt.startTime) : new Date(),
opt.metadata,
),
});
/**
* Processes the detail property of an object using a custom processor function.
* @template T - Object type that may contain a detail property
* @param target - Object containing the detail property to process
* @param processor - Function to transform the detail value
* @returns New object with processed detail property, or original object if no detail
*/
function processDetail<T extends { detail?: unknown }>(
target: T,
processor: (detail: string | object) => string | object,
): T {
if (
target.detail != null &&
(typeof target.detail === 'string' || typeof target.detail === 'object')
) {
return { ...target, detail: processor(target.detail) };
}
return target;
}
function encodeDetailToString<T extends { detail?: unknown }>(
target: T,
): T & { detail?: string } {
return processDetail(target, (detail: string | object) =>
typeof detail === 'object' ? JSON.stringify(detail) : detail,
) as T & { detail?: string };
}
/**
* Decodes a JSON string detail property back to its original object form.
* @param target - Object containing a detail property as a JSON string
* @returns UserTimingDetail with the detail property parsed from JSON
*/
export function decodeDetail<T extends { detail?: string | object }>(
target: T,
): T {
return processDetail(target, detail =>
typeof detail === 'string'
? (JSON.parse(detail) as string | object)
: detail,
);
}
/**
* Encodes object detail properties to JSON strings for storage/transmission.
* @param target - UserTimingDetail object with detail property to encode
* @returns UserTimingDetail with object details converted to JSON strings
*/
export function encodeDetail<T extends { detail?: string | object }>(
target: T,
): T {
return processDetail(
target as T & { detail?: unknown },
(detail: string | object) =>
typeof detail === 'object' ? JSON.stringify(detail) : detail,
);
}
/**
* Decodes a raw trace event with JSON string details back to typed UserTimingTraceEvent.
* Parses detail properties from JSON strings to objects.
* @param event - Raw trace event with string-encoded details
* @returns UserTimingTraceEvent with parsed detail objects
*/
export function decodeTraceEvent({
args,
...rest
}: TraceEventRaw): UserTimingTraceEvent {
if (!args) {
return rest as UserTimingTraceEvent;
}
const processedArgs = decodeDetail(args as { detail: string });
if ('data' in args && args.data && typeof args.data === 'object') {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {
...rest,
args: {
...processedArgs,
data: decodeDetail(args.data as { detail: string }),
},
} as UserTimingTraceEvent;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return { ...rest, args: processedArgs } as UserTimingTraceEvent;
}
/**
* Encodes a UserTimingTraceEvent to raw format with JSON string details.
* Converts object details to JSON strings for storage/transmission.
* @param event - UserTimingTraceEvent with object details
* @returns TraceEventRaw with string-encoded details
*/
export function encodeTraceEvent({
args,
...rest
}: UserTimingTraceEvent): TraceEventRaw {
if (!args) {
return rest as TraceEventRaw;
}
const processedArgs = encodeDetailToString(args as { detail?: unknown });
if ('data' in args && args.data && typeof args.data === 'object') {
const result: TraceEventRaw = {
...rest,
args: {
...processedArgs,
data: encodeDetailToString(args.data as { detail?: unknown }),
},
};
return result;
}
const result: TraceEventRaw = { ...rest, args: processedArgs };
return result;
}