forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarker-schema.js
694 lines (651 loc) · 21.2 KB
/
marker-schema.js
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import * as React from 'react';
import { oneLine } from 'common-tags';
import {
formatNumber,
formatPercent,
formatBytes,
formatSeconds,
formatMilliseconds,
formatTimestamp,
formatMicroseconds,
formatNanoseconds,
} from '../utils/format-numbers';
import { ensureExists } from '../utils/flow';
import type {
CategoryList,
MarkerFormatType,
MarkerSchema,
MarkerSchemaByName,
Marker,
MarkerIndex,
MarkerPayload,
Tid,
Pid,
} from 'firefox-profiler/types';
import type { UniqueStringArray } from '../utils/unique-string-array';
/**
* The marker schema comes from Gecko, and is embedded in the profile. However,
* we may want to define schemas that are front-end only. This is the location
* to do that. The schema will get merged in with the Gecko schema.
*/
export const markerSchemaFrontEndOnly: MarkerSchema[] = [
{
name: 'Jank',
display: ['marker-table', 'marker-chart'],
tooltipLabel: 'Jank – event processing delay',
tableLabel: 'Event processing delay',
data: [
{
label: 'Description',
value: oneLine`
Jank markers show when the main event loop of a thread has been busy. It is
a good indicator that there may be some kind of performance problem that
is worth investigating.
`,
},
],
},
// Note, these can also come from Gecko, but since we have lots of special handling
// for IPC, the Gecko ones get overwritten by this definition.
{
name: 'IPC',
tooltipLabel: 'IPC — {marker.data.niceDirection}',
tableLabel: '{marker.data.messageType} — {marker.data.niceDirection}',
chartLabel: '{marker.data.messageType}',
display: ['marker-chart', 'marker-table', 'timeline-ipc'],
data: [
{ key: 'messageType', label: 'Type', format: 'string', searchable: true },
{ key: 'sync', label: 'Sync', format: 'string' },
{ key: 'sendThreadName', label: 'From', format: 'string' },
{ key: 'recvThreadName', label: 'To', format: 'string' },
{
key: 'otherPid',
label: 'Other Pid',
format: 'pid',
searchable: true,
},
],
},
{
// The network markers are mostly handled with custom logic. But the
// `display` property is used to decide where to display these markers, and
// we need it to hide them from the marker chart.
name: 'Network',
display: ['marker-table', 'marker-chart'],
chartLabel: '{marker.data.URI}',
data: [],
},
];
/**
* For the most part, schema is matched up by the Payload's "type" field,
* but for practical purposes, there are a few other options, see the
* implementation of this function for details.
*/
export function getMarkerSchemaName(
markerSchemaByName: MarkerSchemaByName,
markerName: string,
markerData: MarkerPayload | null
): string {
if (!markerData) {
// Fall back to using the name if no payload exists.
return markerName;
}
const { type } = markerData;
if (type === 'tracing' && markerData.category) {
// TODO - Tracing markers have a duplicate "category" field.
// See issue #2749
// Does a marker schema for the "category" exist?
return markerSchemaByName[markerData.category] === undefined
? // If not, default back to tracing
'tracing'
: // If so, use the category as the schema name.
markerData.category;
}
if (type === 'Text') {
// Text markers are a cheap and easy way to create markers with
// a category. Check for schema if it exists, if not, fallback to
// a Text type marker.
return markerSchemaByName[markerName] === undefined ? 'Text' : markerName;
}
return type;
}
/**
* This function takes the intended marker schema for a marker field, and applies
* the appropriate formatting function.
*/
export function getSchemaFromMarker(
markerSchemaByName: MarkerSchemaByName,
markerName: string,
markerData: MarkerPayload | null
): MarkerSchema | null {
return (
markerSchemaByName[
getMarkerSchemaName(markerSchemaByName, markerName, markerData)
] || null
);
}
/**
* Marker schema can create a dynamic tooltip label. For instance a schema with
* a `tooltipLabel` field of "Event at {marker.data.url}" would create a label based
* off of the "url" property in the payload.
*
* Note that this is only exported for unit tests.
*/
export function parseLabel(
markerSchema: MarkerSchema,
categories: CategoryList,
stringTable: UniqueStringArray,
label: string
): (Marker) => string {
// Split the label on the "{key}" capture groups.
// Each (zero-indexed) even entry will be a raw string label.
// Each (zero-indexed) odd entry will be a key to the payload.
//
// e.g.
// "asdf {marker.name} jkl {marker.data.bytes}"
// -> ["asdf ", "marker.name", " jkl ", "marker.data.bytes"]
//
// "{marker.name} jkl {marker.data.bytes}"
// -> ["", "marker.name", " jkl ", "marker.data.bytes"];
//
// "{marker.name}"
// -> ["", "marker.name", ""];
const splits = label.split(/{([^}]+)}/);
// { } Split anytime text is in brackets.
// ( ) Capture the text inside the brackets.
// [^}]+ Match any character that is not a }.
if (splits.length === 1) {
// Return the label.
return () => label;
}
/**
* Notify the user via the console if there is a parse error, but don't crash
* anything for the end user. Return a blank string.
*/
function parseError(label: string, part: string) {
console.error(oneLine`
Error processing the label "${label}" because of the ${part}.
Currently the labels in the marker schema take the form of
"marker.data.keyName" or "marker.startTime". No other type
of access is currently supported.
`);
return () => '';
}
// This is a list of functions that will compute each part of the label.
const computeLabelParts: Array<(Marker) => string> = splits.map((part, i) => {
if (i % 2 === 0) {
// This is a normal string part. Return it.
// Given: "Marker information: {marker.name} – {marker.data.info}"
// Handle: ^^^^^^^^^^^^^^^^^^^^ ^^^
return () => part;
}
// Now consider each keyed property:
// Given: "Marker information: {marker.name} – {marker.data.info}"
// Handle: ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
const keys = part.trim().split('.');
if (keys.length !== 2 && keys.length !== 3) {
// The following examples would trigger this error:
// Given: "Marker information: {name} – {marker.data.info.subinfo}"
// Handle: ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
return parseError(label, part);
}
const [marker, markerKey, payloadKey] = keys;
if (marker !== 'marker') {
// The following examples would trigger this error:
// Given: "Value: {property.name}"
// Handle: ^^^^^^^^
return parseError(label, part);
}
if (keys.length === 2) {
// Access parts of the payload
// Given: "Marker information: {marker.name} – {marker.data.info}"
// Handle: ^^^^^^^^^^^
switch (markerKey) {
case 'start':
return (marker) => formatTimestamp(marker.start);
case 'end':
return (marker) =>
marker.end === null ? 'unknown' : formatTimestamp(marker.end);
case 'duration':
return (marker) =>
marker.end === null
? 'unknown'
: formatTimestamp(marker.end - marker.start);
case 'name':
return (marker) => marker.name;
case 'category':
return (marker) => categories[marker.category].name;
case 'data':
default:
return parseError(label, part);
}
}
if (markerKey === 'data') {
// This is accessing the payload.
// Given: "Marker information: {marker.name} – {marker.data.info}"
// Handle: ^^^^^^^^^^^^^^^^
let format = null;
for (const rule of markerSchema.data) {
// The rule.value === undefined line is odd mainly because Flow was having trouble
// refining the type.
if (rule.value === undefined && rule.key === payloadKey) {
format = rule.format;
break;
}
}
return (marker) => {
if (!marker.data) {
// There was no data.
return '';
}
const value = marker.data[payloadKey];
if (value === undefined || value === null) {
// This would return "undefined" or "null" otherwise.
return '';
}
return format
? formatFromMarkerSchema(
markerSchema.name,
format,
value,
stringTable
)
: value;
};
}
return parseError(label, part);
});
return (marker: Marker) => {
let result: string = '';
for (const computeLabelPart of computeLabelParts) {
result += computeLabelPart(marker);
}
return result;
};
}
type LabelKey = 'tooltipLabel' | 'tableLabel' | 'chartLabel' | 'copyLabel';
// If no label making rule, these functions provide the fallbacks for how
// to label things. It also allows for a place to do some custom handling
// in the cases where the marker schema is not enough.
const fallbacks: { [LabelKey]: (Marker) => string } = {
tooltipLabel: (marker) => marker.name,
chartLabel: (_marker) => '',
tableLabel: (marker: Marker) => {
let description = '';
if (marker.data) {
const data = marker.data;
switch (data.type) {
case 'FileIO':
if (data.source) {
description = `(${data.source}) `;
}
description += data.operation;
if (data.filename) {
description = data.operation
? `${description} — ${data.filename}`
: data.filename;
}
break;
default:
}
}
return description;
},
copyLabel: (marker) => marker.name,
};
/**
* Marker labels are computed dynamically. In an effort to keep this process efficient
* in a reactive environment, this function creates a memoized function that takes a
* MarkerIndex and returns the label for a given area. This label is cached between
* calls. The label maker function parses the marker schema to determine how to process
* and display the label.
*
* This function should only be used behind a selector.
*/
export function getLabelGetter(
getMarker: (MarkerIndex) => Marker,
markerSchemaList: MarkerSchema[],
markerSchemaByName: MarkerSchemaByName,
categoryList: CategoryList,
stringTable: UniqueStringArray,
labelKey: LabelKey
): (MarkerIndex) => string {
// Build up a list of label functions, that are tied to the schema name.
const labelFns: Map<string, (Marker) => string> = new Map();
const markerNamePrefixRe = /^{marker.name}\s[-—]\s/;
for (const schema of markerSchemaList) {
let labelString;
if (labelKey === 'copyLabel') {
// When copying a marker description, use the marker table label.
labelString = schema.tableLabel;
if (labelString && !markerNamePrefixRe.test(labelString)) {
// Ensure the label starts with the marker name.
labelString = '{marker.name} — ' + labelString;
}
} else {
labelString = schema[labelKey];
// The marker table used to not show the marker name, so all marker
// schemas included the marker name as the first part of their table
// label. Now that the marker table has a name column, we can remove
// this prefix to avoid duplication.
if (labelString && labelKey === 'tableLabel') {
labelString = labelString.replace(markerNamePrefixRe, '');
}
}
if (labelString) {
labelFns.set(
schema.name,
parseLabel(schema, categoryList, stringTable, labelString)
);
}
}
const getFallbackLabel = ensureExists(
fallbacks[labelKey],
'Unable to find a fallback label function.'
);
// Cache the labels as they are created.
const markerIndexToLabel: Map<MarkerIndex, string> = new Map();
return (markerIndex: MarkerIndex) => {
let label = markerIndexToLabel.get(markerIndex);
// No label exists, it will have to be generated for the first time.
if (label === undefined) {
const marker = getMarker(markerIndex);
const schemaName = getMarkerSchemaName(
markerSchemaByName,
marker.name,
marker.data
);
const applyLabel = labelFns.get(schemaName);
label = applyLabel
? // A label function is available, apply it.
applyLabel(marker)
: // There is no label function, fall back to a different strategy.
getFallbackLabel(marker);
// Make sure and cache this, so that the result can be re-used.
markerIndexToLabel.set(markerIndex, label);
}
return label;
};
}
/**
* This function formats a string from a marker type and a value.
* If you wish to get markup instead, have a look at
* formatMarkupFromMarkerSchema below.
*/
export function formatFromMarkerSchema(
markerType: string,
format: MarkerFormatType,
value: any,
stringTable: UniqueStringArray,
threadIdToNameMap?: Map<Tid, string>,
processIdToNameMap?: Map<Pid, string>
): string {
if (value === undefined || value === null) {
console.warn(
`Formatting ${value} for ${markerType} with format ${JSON.stringify(
format
)}`
);
return '(empty)';
}
if (typeof format === 'object') {
switch (format.type) {
case 'table': {
const { columns } = format;
if (!(value instanceof Array)) {
throw new Error('Expected an array for table type');
}
const hasHeader = columns.some((column) => column.label);
const rows = hasHeader
? [columns.map((x) => x.label || '(empty)')]
: [];
const cellRows = value.map((row, i) => {
if (!(row instanceof Array)) {
throw new Error('Expected an array for table row');
}
if (row.length !== columns.length) {
throw new Error(
`Row ${i} length doesn't match column count (row: ${row.length}, cols: ${columns.length})`
);
}
return row.map((cell, j) => {
const { format } = columns[j];
return formatFromMarkerSchema(
markerType,
format || 'string',
cell,
stringTable,
threadIdToNameMap,
processIdToNameMap
);
});
});
rows.push(...cellRows);
return rows.map((row) => `(${row.join(', ')})`).join(',');
}
default:
throw new Error(
`Unknown format type ${JSON.stringify((format.type: empty))}`
);
}
}
switch (format) {
case 'url':
case 'file-path':
case 'sanitized-string':
case 'string':
// Make sure a non-empty string is returned here.
return String(value) || '(empty)';
case 'unique-string':
case 'flow-id':
case 'terminating-flow-id':
return stringTable.getString(value, '(empty)');
case 'duration':
case 'time':
return formatTimestamp(value);
case 'seconds':
return formatSeconds(value);
case 'milliseconds':
return formatMilliseconds(value);
case 'microseconds':
return formatMicroseconds(value);
case 'nanoseconds':
return formatNanoseconds(value);
case 'bytes':
return formatBytes(value);
case 'integer':
return formatNumber(value, 0, 0);
case 'decimal':
return formatNumber(value);
case 'percentage':
return formatPercent(value);
case 'pid':
return processIdToNameMap && processIdToNameMap.has(value)
? `${ensureExists(processIdToNameMap.get(value))} (${value})`
: `PID: ${value}`;
case 'tid':
return threadIdToNameMap && threadIdToNameMap.has(value)
? `${ensureExists(threadIdToNameMap.get(value))} (${value})`
: `TID: ${value}`;
case 'list':
if (!(value instanceof Array)) {
throw new Error('Expected an array for list format');
}
return value
.map((v) =>
formatFromMarkerSchema(markerType, 'string', v, stringTable)
)
.join(', ');
default:
console.warn(
`A marker schema of type "${markerType}" had an unknown format ${JSON.stringify(
(format: empty)
)}`
);
return value;
}
}
// This regexp is used to test for URLs and remove their scheme for display.
const URL_SCHEME_REGEXP = /^http(s?):\/\//;
/**
* This function may return structured markup for some types suchs as table,
* list, or urls. For other types this falls back to formatFromMarkerSchema
* above.
*/
export function formatMarkupFromMarkerSchema(
markerType: string,
format: MarkerFormatType,
value: any,
stringTable: UniqueStringArray,
threadIdToNameMap?: Map<Tid, string>,
processIdToNameMap?: Map<Pid, string>
): React.Element<any> | string {
if (value === undefined || value === null) {
console.warn(`Formatting ${value} for ${JSON.stringify(markerType)}`);
return '(empty)';
}
if (format !== 'url' && typeof format !== 'object' && format !== 'list') {
return formatFromMarkerSchema(
markerType,
format,
value,
stringTable,
threadIdToNameMap,
processIdToNameMap
);
}
if (typeof format === 'object') {
switch (format.type) {
case 'table': {
const { columns } = format;
if (!(value instanceof Array)) {
throw new Error('Expected an array for table type');
}
const hasHeader = columns.some((column) => column.label);
return (
<table className="marker-table-value">
{hasHeader ? (
<thead>
<tr>
{columns.map((col, i) => (
<th key={i}>{col.label || ''}</th>
))}
</tr>
</thead>
) : null}
<tbody>
{value.map((row, i) => {
if (!(row instanceof Array)) {
throw new Error('Expected an array for table row');
}
if (row.length !== columns.length) {
throw new Error(
`Row ${i} length doesn't match column count (row: ${row.length}, cols: ${columns.length})`
);
}
return (
<tr key={i}>
{row.map((cell, i) => {
return (
<td key={i}>
{formatMarkupFromMarkerSchema(
markerType,
columns[i].type || 'string',
cell,
stringTable,
threadIdToNameMap,
processIdToNameMap
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
}
default:
throw new Error(
`Unknown format type ${JSON.stringify((format: empty))}`
);
}
}
switch (format) {
case 'list':
if (!(value instanceof Array)) {
throw new Error('Expected an array for list format');
}
return (
<ul className="marker-list-value">
{value.map((entry, i) => (
<li key={i}>
{formatFromMarkerSchema(
markerType,
'string',
value[i],
stringTable
)}
</li>
))}
</ul>
);
case 'url': {
if (!URL_SCHEME_REGEXP.test(value)) {
return value;
}
return (
<a
href={value}
target="_blank"
rel="noreferrer"
className="marker-link-value"
>
{value.replace(URL_SCHEME_REGEXP, '')}
</a>
);
}
default:
throw new Error(`Unknown format type ${JSON.stringify((format: empty))}`);
}
}
/**
* Takes a marker and a RegExp and checks if any of its `searchable` marker
* payload fields match the search regular expression.
*/
export function markerPayloadMatchesSearch(
markerSchema: MarkerSchema,
marker: Marker,
stringTable: UniqueStringArray,
testFun: (string, string) => boolean
): boolean {
const { data } = marker;
if (!data) {
return false;
}
// Check if searchable fields match the search regular expression.
for (const payloadField of markerSchema.data) {
if (payloadField.searchable) {
let value = data[payloadField.key];
if (
payloadField.format === 'unique-string' ||
payloadField.format === 'flow-id' ||
payloadField.format === 'terminating-flow-id'
) {
value = stringTable.getString(value);
}
if (value === undefined || value === null || value === '') {
continue;
}
if (testFun(value, payloadField.key)) {
return true;
}
}
}
return false;
}