/
preprocessData.js
1165 lines (1031 loc) · 37.5 KB
/
preprocessData.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {
importFromChromeTimeline,
Flamechart as SpeedscopeFlamechart,
} from '@elg/speedscope';
import type {TimelineEvent} from '@elg/speedscope';
import type {
ErrorStackFrame,
BatchUID,
Flamechart,
Milliseconds,
NativeEvent,
NetworkMeasure,
Phase,
ReactLane,
ReactComponentMeasure,
ReactComponentMeasureType,
ReactMeasure,
ReactMeasureType,
TimelineData,
SchedulingEvent,
SuspenseEvent,
} from '../types';
import {
REACT_TOTAL_NUM_LANES,
SCHEDULING_PROFILER_VERSION,
SNAPSHOT_MAX_HEIGHT,
} from '../constants';
import InvalidProfileError from './InvalidProfileError';
import {getBatchRange} from '../utils/getBatchRange';
import ErrorStackParser from 'error-stack-parser';
type MeasureStackElement = {|
type: ReactMeasureType,
depth: number,
measure: ReactMeasure,
startTime: Milliseconds,
stopTime?: Milliseconds,
|};
type ProcessorState = {|
asyncProcessingPromises: Promise<any>[],
batchUID: BatchUID,
currentReactComponentMeasure: ReactComponentMeasure | null,
internalModuleCurrentStackFrame: ErrorStackFrame | null,
internalModuleStackStringSet: Set<string>,
measureStack: MeasureStackElement[],
nativeEventStack: NativeEvent[],
nextRenderShouldGenerateNewBatchID: boolean,
potentialLongEvents: Array<[NativeEvent, BatchUID]>,
potentialLongNestedUpdate: SchedulingEvent | null,
potentialLongNestedUpdates: Array<[SchedulingEvent, BatchUID]>,
potentialSuspenseEventsOutsideOfTransition: Array<
[SuspenseEvent, ReactLane[]],
>,
requestIdToNetworkMeasureMap: Map<string, NetworkMeasure>,
uidCounter: BatchUID,
unresolvedSuspenseEvents: Map<string, SuspenseEvent>,
|};
const NATIVE_EVENT_DURATION_THRESHOLD = 20;
const NESTED_UPDATE_DURATION_THRESHOLD = 20;
const WARNING_STRINGS = {
LONG_EVENT_HANDLER:
'An event handler scheduled a big update with React. Consider using the Transition API to defer some of this work.',
NESTED_UPDATE:
'A big nested update was scheduled during layout. ' +
'Nested updates require React to re-render synchronously before the browser can paint. ' +
'Consider delaying this update by moving it to a passive effect (useEffect).',
SUSPEND_DURING_UPDATE:
'A component suspended during an update which caused a fallback to be shown. ' +
"Consider using the Transition API to avoid hiding components after they've been mounted.",
};
// Exported for tests
export function getLanesFromTransportDecimalBitmask(
laneBitmaskString: string,
): ReactLane[] {
const laneBitmask = parseInt(laneBitmaskString, 10);
// As negative numbers are stored in two's complement format, our bitmask
// checks will be thrown off by them.
if (laneBitmask < 0) {
return [];
}
const lanes = [];
let powersOfTwo = 0;
while (powersOfTwo <= REACT_TOTAL_NUM_LANES) {
if ((1 << powersOfTwo) & laneBitmask) {
lanes.push(powersOfTwo);
}
powersOfTwo++;
}
return lanes;
}
function updateLaneToLabelMap(
profilerData: TimelineData,
laneLabelTuplesString: string,
): void {
// These marks appear multiple times in the data;
// We only need to extact them once.
if (profilerData.laneToLabelMap.size === 0) {
const laneLabelTuples = laneLabelTuplesString.split(',');
for (let laneIndex = 0; laneIndex < laneLabelTuples.length; laneIndex++) {
// The numeric lane value (e.g. 64) isn't important.
// The profiler parses and stores the lane's position within the bitmap,
// (e.g. lane 1 is index 0, lane 16 is index 4).
profilerData.laneToLabelMap.set(laneIndex, laneLabelTuples[laneIndex]);
}
}
}
let profilerVersion = null;
function getLastType(stack: $PropertyType<ProcessorState, 'measureStack'>) {
if (stack.length > 0) {
const {type} = stack[stack.length - 1];
return type;
}
return null;
}
function getDepth(stack: $PropertyType<ProcessorState, 'measureStack'>) {
if (stack.length > 0) {
const {depth, type} = stack[stack.length - 1];
return type === 'render-idle' ? depth : depth + 1;
}
return 0;
}
function markWorkStarted(
type: ReactMeasureType,
startTime: Milliseconds,
lanes: ReactLane[],
currentProfilerData: TimelineData,
state: ProcessorState,
) {
const {batchUID, measureStack} = state;
const depth = getDepth(measureStack);
const measure: ReactMeasure = {
type,
batchUID,
depth,
lanes,
timestamp: startTime,
duration: 0,
};
state.measureStack.push({depth, measure, startTime, type});
// This array is pre-initialized when the batchUID is generated.
const measures = currentProfilerData.batchUIDToMeasuresMap.get(batchUID);
if (measures != null) {
measures.push(measure);
} else {
currentProfilerData.batchUIDToMeasuresMap.set(state.batchUID, [measure]);
}
// This array is pre-initialized before processing starts.
lanes.forEach(lane => {
((currentProfilerData.laneToReactMeasureMap.get(
lane,
): any): ReactMeasure[]).push(measure);
});
}
function markWorkCompleted(
type: ReactMeasureType,
stopTime: Milliseconds,
currentProfilerData: TimelineData,
stack: $PropertyType<ProcessorState, 'measureStack'>,
) {
if (stack.length === 0) {
console.error(
'Unexpected type "%s" completed at %sms while stack is empty.',
type,
stopTime,
);
// Ignore work "completion" user timing mark that doesn't complete anything
return;
}
const last = stack[stack.length - 1];
if (last.type !== type) {
console.error(
'Unexpected type "%s" completed at %sms before "%s" completed.',
type,
stopTime,
last.type,
);
}
const {measure, startTime} = stack.pop();
if (!measure) {
console.error('Could not find matching measure for type "%s".', type);
}
// $FlowFixMe This property should not be writable outside of this function.
measure.duration = stopTime - startTime;
}
function throwIfIncomplete(
type: ReactMeasureType,
stack: $PropertyType<ProcessorState, 'measureStack'>,
) {
const lastIndex = stack.length - 1;
if (lastIndex >= 0) {
const last = stack[lastIndex];
if (last.stopTime === undefined && last.type === type) {
throw new InvalidProfileError(
`Unexpected type "${type}" started before "${last.type}" completed.`,
);
}
}
}
function processEventDispatch(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const data = event.args.data;
const type = data.type;
if (type.startsWith('react-')) {
const stackTrace = data.stackTrace;
if (stackTrace) {
const topFrame = stackTrace[stackTrace.length - 1];
if (topFrame.url.includes('/react-dom.')) {
// Filter out fake React events dispatched by invokeGuardedCallbackDev.
return;
}
}
}
// Reduce noise from events like DOMActivate, load/unload, etc. which are usually not relevant
if (
type === 'blur' ||
type === 'click' ||
type === 'input' ||
type.startsWith('focus') ||
type.startsWith('key') ||
type.startsWith('mouse') ||
type.startsWith('pointer')
) {
const duration = event.dur / 1000;
let depth = 0;
while (state.nativeEventStack.length > 0) {
const prevNativeEvent =
state.nativeEventStack[state.nativeEventStack.length - 1];
const prevStopTime = prevNativeEvent.timestamp + prevNativeEvent.duration;
if (timestamp < prevStopTime) {
depth = prevNativeEvent.depth + 1;
break;
} else {
state.nativeEventStack.pop();
}
}
const nativeEvent = {
depth,
duration,
timestamp,
type,
warning: null,
};
profilerData.nativeEvents.push(nativeEvent);
// Keep track of curent event in case future ones overlap.
// We separate them into different vertical lanes in this case.
state.nativeEventStack.push(nativeEvent);
}
}
function processResourceFinish(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const requestId = event.args.data.requestId;
const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId);
if (networkMeasure != null) {
networkMeasure.finishTimestamp = timestamp;
if (networkMeasure.firstReceivedDataTimestamp === 0) {
networkMeasure.firstReceivedDataTimestamp = timestamp;
}
if (networkMeasure.lastReceivedDataTimestamp === 0) {
networkMeasure.lastReceivedDataTimestamp = timestamp;
}
// Clean up now that the resource is done.
state.requestIdToNetworkMeasureMap.delete(event.args.data.requestId);
}
}
function processResourceReceivedData(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const requestId = event.args.data.requestId;
const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId);
if (networkMeasure != null) {
if (networkMeasure.firstReceivedDataTimestamp === 0) {
networkMeasure.firstReceivedDataTimestamp = timestamp;
}
networkMeasure.lastReceivedDataTimestamp = timestamp;
networkMeasure.finishTimestamp = timestamp;
}
}
function processResourceReceiveResponse(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const requestId = event.args.data.requestId;
const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId);
if (networkMeasure != null) {
networkMeasure.receiveResponseTimestamp = timestamp;
}
}
function processScreenshot(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const encodedSnapshot = event.args.snapshot; // Base 64 encoded
const snapshot = {
height: 0,
image: null,
imageSource: `data:image/png;base64,${encodedSnapshot}`,
timestamp,
width: 0,
};
// Delay processing until we've extracted snapshot dimensions.
let resolveFn = ((null: any): Function);
state.asyncProcessingPromises.push(
new Promise(resolve => {
resolveFn = resolve;
}),
);
// Parse the Base64 image data to determine native size.
// This will be used later to scale for display within the thumbnail strip.
fetch(snapshot.imageSource)
.then(response => response.blob())
.then(blob => {
// $FlowFixMe createImageBitmap
createImageBitmap(blob).then(bitmap => {
snapshot.height = bitmap.height;
snapshot.width = bitmap.width;
resolveFn();
});
});
profilerData.snapshots.push(snapshot);
}
function processResourceSendRequest(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const data = event.args.data;
const requestId = data.requestId;
const availableDepths = new Array(
state.requestIdToNetworkMeasureMap.size + 1,
).fill(true);
state.requestIdToNetworkMeasureMap.forEach(({depth}) => {
availableDepths[depth] = false;
});
let depth = 0;
for (let i = 0; i < availableDepths.length; i++) {
if (availableDepths[i]) {
depth = i;
break;
}
}
const networkMeasure: NetworkMeasure = {
depth,
finishTimestamp: 0,
firstReceivedDataTimestamp: 0,
lastReceivedDataTimestamp: 0,
requestId,
requestMethod: data.requestMethod,
priority: data.priority,
sendRequestTimestamp: timestamp,
receiveResponseTimestamp: 0,
url: data.url,
};
state.requestIdToNetworkMeasureMap.set(requestId, networkMeasure);
profilerData.networkMeasures.push(networkMeasure);
networkMeasure.sendRequestTimestamp = timestamp;
}
function processTimelineEvent(
event: TimelineEvent,
/** Finalized profiler data up to `event`. May be mutated. */
currentProfilerData: TimelineData,
/** Intermediate processor state. May be mutated. */
state: ProcessorState,
) {
const {cat, name, ts, ph} = event;
const startTime = (ts - currentProfilerData.startTime) / 1000;
switch (cat) {
case 'disabled-by-default-devtools.screenshot':
processScreenshot(event, startTime, currentProfilerData, state);
break;
case 'devtools.timeline':
switch (name) {
case 'EventDispatch':
processEventDispatch(event, startTime, currentProfilerData, state);
break;
case 'ResourceFinish':
processResourceFinish(event, startTime, currentProfilerData, state);
break;
case 'ResourceReceivedData':
processResourceReceivedData(
event,
startTime,
currentProfilerData,
state,
);
break;
case 'ResourceReceiveResponse':
processResourceReceiveResponse(
event,
startTime,
currentProfilerData,
state,
);
break;
case 'ResourceSendRequest':
processResourceSendRequest(
event,
startTime,
currentProfilerData,
state,
);
break;
}
break;
case 'blink.user_timing':
if (name.startsWith('--react-version-')) {
const [reactVersion] = name.substr(16).split('-');
currentProfilerData.reactVersion = reactVersion;
} else if (name.startsWith('--profiler-version-')) {
const [versionString] = name.substr(19).split('-');
profilerVersion = parseInt(versionString, 10);
if (profilerVersion !== SCHEDULING_PROFILER_VERSION) {
throw new InvalidProfileError(
`This version of profiling data (${versionString}) is not supported by the current profiler.`,
);
}
} else if (name.startsWith('--react-lane-labels-')) {
const [laneLabelTuplesString] = name.substr(20).split('-');
updateLaneToLabelMap(currentProfilerData, laneLabelTuplesString);
} else if (name.startsWith('--component-')) {
processReactComponentMeasure(
name,
startTime,
currentProfilerData,
state,
);
} else if (name.startsWith('--schedule-render-')) {
const [laneBitmaskString] = name.substr(18).split('-');
currentProfilerData.schedulingEvents.push({
type: 'schedule-render',
lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString),
timestamp: startTime,
warning: null,
});
} else if (name.startsWith('--schedule-forced-update-')) {
const [laneBitmaskString, componentName] = name.substr(25).split('-');
const forceUpdateEvent = {
type: 'schedule-force-update',
lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString),
componentName,
timestamp: startTime,
warning: null,
};
// If this is a nested update, make a note of it.
// Once we're done processing events, we'll check to see if it was a long update and warn about it.
if (state.measureStack.find(({type}) => type === 'commit')) {
state.potentialLongNestedUpdate = forceUpdateEvent;
}
currentProfilerData.schedulingEvents.push(forceUpdateEvent);
} else if (name.startsWith('--schedule-state-update-')) {
const [laneBitmaskString, componentName] = name.substr(24).split('-');
const stateUpdateEvent = {
type: 'schedule-state-update',
lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString),
componentName,
timestamp: startTime,
warning: null,
};
// If this is a nested update, make a note of it.
// Once we're done processing events, we'll check to see if it was a long update and warn about it.
if (state.measureStack.find(({type}) => type === 'commit')) {
state.potentialLongNestedUpdate = stateUpdateEvent;
}
currentProfilerData.schedulingEvents.push(stateUpdateEvent);
} else if (name.startsWith('--error-')) {
const [componentName, phase, message] = name.substr(8).split('-');
currentProfilerData.thrownErrors.push({
componentName,
message,
phase: ((phase: any): Phase),
timestamp: startTime,
type: 'thrown-error',
});
} else if (name.startsWith('--suspense-suspend-')) {
const [
id,
componentName,
phase,
laneBitmaskString,
promiseName,
] = name.substr(19).split('-');
const lanes = getLanesFromTransportDecimalBitmask(laneBitmaskString);
const availableDepths = new Array(
state.unresolvedSuspenseEvents.size + 1,
).fill(true);
state.unresolvedSuspenseEvents.forEach(({depth}) => {
availableDepths[depth] = false;
});
let depth = 0;
for (let i = 0; i < availableDepths.length; i++) {
if (availableDepths[i]) {
depth = i;
break;
}
}
// TODO (timeline) Maybe we should calculate depth in post,
// so unresolved Suspense requests don't take up space.
// We can't know if they'll be resolved or not at this point.
// We'll just give them a default (fake) duration width.
const suspenseEvent = {
componentName,
depth,
duration: null,
id,
phase: ((phase: any): Phase),
promiseName: promiseName || null,
resolution: 'unresolved',
timestamp: startTime,
type: 'suspense',
warning: null,
};
if (phase === 'update') {
// If a component suspended during an update, we should verify that it was during a transition.
// We need the lane metadata to verify this though.
// Since that data is only logged during commit, we may not have it yet.
// Store these events for post-processing then.
state.potentialSuspenseEventsOutsideOfTransition.push([
suspenseEvent,
lanes,
]);
}
currentProfilerData.suspenseEvents.push(suspenseEvent);
state.unresolvedSuspenseEvents.set(id, suspenseEvent);
} else if (name.startsWith('--suspense-resolved-')) {
const [id] = name.substr(20).split('-');
const suspenseEvent = state.unresolvedSuspenseEvents.get(id);
if (suspenseEvent != null) {
state.unresolvedSuspenseEvents.delete(id);
suspenseEvent.duration = startTime - suspenseEvent.timestamp;
suspenseEvent.resolution = 'resolved';
}
} else if (name.startsWith('--suspense-rejected-')) {
const [id] = name.substr(20).split('-');
const suspenseEvent = state.unresolvedSuspenseEvents.get(id);
if (suspenseEvent != null) {
state.unresolvedSuspenseEvents.delete(id);
suspenseEvent.duration = startTime - suspenseEvent.timestamp;
suspenseEvent.resolution = 'rejected';
}
} else if (name.startsWith('--render-start-')) {
if (state.nextRenderShouldGenerateNewBatchID) {
state.nextRenderShouldGenerateNewBatchID = false;
state.batchUID = ((state.uidCounter++: any): BatchUID);
}
// If this render is the result of a nested update, make a note of it.
// Once we're done processing events, we'll check to see if it was a long update and warn about it.
if (state.potentialLongNestedUpdate !== null) {
state.potentialLongNestedUpdates.push([
state.potentialLongNestedUpdate,
state.batchUID,
]);
state.potentialLongNestedUpdate = null;
}
const [laneBitmaskString] = name.substr(15).split('-');
throwIfIncomplete('render', state.measureStack);
if (getLastType(state.measureStack) !== 'render-idle') {
markWorkStarted(
'render-idle',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
}
markWorkStarted(
'render',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
for (let i = 0; i < state.nativeEventStack.length; i++) {
const nativeEvent = state.nativeEventStack[i];
const stopTime = nativeEvent.timestamp + nativeEvent.duration;
// If React work was scheduled during an event handler, and the event had a long duration,
// it might be because the React render was long and stretched the event.
// It might also be that the React work was short and that something else stretched the event.
// Make a note of this event for now and we'll examine the batch of React render work later.
// (We can't know until we're done processing the React update anyway.)
if (stopTime > startTime) {
state.potentialLongEvents.push([nativeEvent, state.batchUID]);
}
}
} else if (
name.startsWith('--render-stop') ||
name.startsWith('--render-yield')
) {
markWorkCompleted(
'render',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--commit-start-')) {
state.nextRenderShouldGenerateNewBatchID = true;
const [laneBitmaskString] = name.substr(15).split('-');
markWorkStarted(
'commit',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
} else if (name.startsWith('--commit-stop')) {
markWorkCompleted(
'commit',
startTime,
currentProfilerData,
state.measureStack,
);
markWorkCompleted(
'render-idle',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--layout-effects-start-')) {
const [laneBitmaskString] = name.substr(23).split('-');
markWorkStarted(
'layout-effects',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
} else if (name.startsWith('--layout-effects-stop')) {
markWorkCompleted(
'layout-effects',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--passive-effects-start-')) {
const [laneBitmaskString] = name.substr(24).split('-');
markWorkStarted(
'passive-effects',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
} else if (name.startsWith('--passive-effects-stop')) {
markWorkCompleted(
'passive-effects',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--react-internal-module-start-')) {
const stackFrameStart = name.substr(30);
if (!state.internalModuleStackStringSet.has(stackFrameStart)) {
state.internalModuleStackStringSet.add(stackFrameStart);
const parsedStackFrameStart = parseStackFrame(stackFrameStart);
state.internalModuleCurrentStackFrame = parsedStackFrameStart;
}
} else if (name.startsWith('--react-internal-module-stop-')) {
const stackFrameStop = name.substr(29);
if (!state.internalModuleStackStringSet.has(stackFrameStop)) {
state.internalModuleStackStringSet.add(stackFrameStop);
const parsedStackFrameStop = parseStackFrame(stackFrameStop);
if (
parsedStackFrameStop !== null &&
state.internalModuleCurrentStackFrame !== null
) {
const parsedStackFrameStart = state.internalModuleCurrentStackFrame;
state.internalModuleCurrentStackFrame = null;
const range = [parsedStackFrameStart, parsedStackFrameStop];
const ranges = currentProfilerData.internalModuleSourceToRanges.get(
parsedStackFrameStart.fileName,
);
if (ranges == null) {
currentProfilerData.internalModuleSourceToRanges.set(
parsedStackFrameStart.fileName,
[range],
);
} else {
ranges.push(range);
}
}
}
} else if (ph === 'R' || ph === 'n') {
// User Timing mark
currentProfilerData.otherUserTimingMarks.push({
name,
timestamp: startTime,
});
} else if (ph === 'b') {
// TODO: Begin user timing measure
} else if (ph === 'e') {
// TODO: End user timing measure
} else if (ph === 'i' || ph === 'I') {
// Instant events.
// Note that the capital "I" is a deprecated value that exists in Chrome Canary traces.
} else {
throw new InvalidProfileError(
`Unrecognized event ${JSON.stringify(
event,
)}! This is likely a bug in this profiler tool.`,
);
}
break;
}
}
function assertNoOverlappingComponentMeasure(state: ProcessorState) {
if (state.currentReactComponentMeasure !== null) {
console.error(
'Component measure started while another measure in progress:',
state.currentReactComponentMeasure,
);
}
}
function assertCurrentComponentMeasureType(
state: ProcessorState,
type: ReactComponentMeasureType,
): void {
if (state.currentReactComponentMeasure === null) {
console.error(
`Component measure type "${type}" stopped while no measure was in progress`,
);
} else if (state.currentReactComponentMeasure.type !== type) {
console.error(
`Component measure type "${type}" stopped while type ${state.currentReactComponentMeasure.type} in progress`,
);
}
}
function processReactComponentMeasure(
name: string,
startTime: Milliseconds,
currentProfilerData: TimelineData,
state: ProcessorState,
): void {
if (name.startsWith('--component-render-start-')) {
const [componentName] = name.substr(25).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'render',
warning: null,
};
} else if (name === '--component-render-stop') {
assertCurrentComponentMeasureType(state, 'render');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-layout-effect-mount-start-')) {
const [componentName] = name.substr(38).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'layout-effect-mount',
warning: null,
};
} else if (name === '--component-layout-effect-mount-stop') {
assertCurrentComponentMeasureType(state, 'layout-effect-mount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-layout-effect-unmount-start-')) {
const [componentName] = name.substr(40).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'layout-effect-unmount',
warning: null,
};
} else if (name === '--component-layout-effect-unmount-stop') {
assertCurrentComponentMeasureType(state, 'layout-effect-unmount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-passive-effect-mount-start-')) {
const [componentName] = name.substr(39).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'passive-effect-mount',
warning: null,
};
} else if (name === '--component-passive-effect-mount-stop') {
assertCurrentComponentMeasureType(state, 'passive-effect-mount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-passive-effect-unmount-start-')) {
const [componentName] = name.substr(41).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'passive-effect-unmount',
warning: null,
};
} else if (name === '--component-passive-effect-unmount-stop') {
assertCurrentComponentMeasureType(state, 'passive-effect-unmount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
}
}
function preprocessFlamechart(rawData: TimelineEvent[]): Flamechart {
let parsedData;
try {
parsedData = importFromChromeTimeline(rawData, 'react-devtools');
} catch (error) {
// Assume any Speedscope errors are caused by bad profiles
const errorToRethrow = new InvalidProfileError(error.message);
errorToRethrow.stack = error.stack;
throw errorToRethrow;
}
const profile = parsedData.profiles[0]; // TODO: Choose the main CPU thread only
const speedscopeFlamechart = new SpeedscopeFlamechart({
getTotalWeight: profile.getTotalWeight.bind(profile),
forEachCall: profile.forEachCall.bind(profile),
formatValue: profile.formatValue.bind(profile),
getColorBucketForFrame: () => 0,
});
const flamechart: Flamechart = speedscopeFlamechart.getLayers().map(layer =>
layer.map(({start, end, node: {frame: {name, file, line, col}}}) => ({
name,
timestamp: start / 1000,
duration: (end - start) / 1000,
scriptUrl: file,
locationLine: line,
locationColumn: col,
})),
);
return flamechart;
}
function parseStackFrame(stackFrame: string): ErrorStackFrame | null {
const error = new Error();
error.stack = stackFrame;
const frames = ErrorStackParser.parse(error);
return frames.length === 1 ? frames[0] : null;
}
export default async function preprocessData(