-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathflamegraph.tsx
1521 lines (1363 loc) · 51 KB
/
flamegraph.tsx
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
import type {ReactElement} from 'react';
import {
Fragment,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useState,
} from 'react';
import * as Sentry from '@sentry/react';
import {mat3, vec2} from 'gl-matrix';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import {ProfileDragDropImport} from 'sentry/components/profiling/flamegraph/flamegraphOverlays/profileDragDropImport';
import {FlamegraphOptionsMenu} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphOptionsMenu';
import {FlamegraphSearch} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphSearch';
import type {FlamegraphThreadSelectorProps} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphThreadSelector';
import {FlamegraphThreadSelector} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphThreadSelector';
import {FlamegraphToolbar} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphToolbar';
import type {FlamegraphViewSelectMenuProps} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphViewSelectMenu';
import {FlamegraphViewSelectMenu} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphViewSelectMenu';
import {FlamegraphZoomView} from 'sentry/components/profiling/flamegraph/flamegraphZoomView';
import {FlamegraphZoomViewMinimap} from 'sentry/components/profiling/flamegraph/flamegraphZoomViewMinimap';
import {t} from 'sentry/locale';
import type {RequestState} from 'sentry/types/core';
import type {EntrySpans, EventTransaction} from 'sentry/types/event';
import {EntryType} from 'sentry/types/event';
import {defined} from 'sentry/utils';
import {
CanvasPoolManager,
useCanvasScheduler,
} from 'sentry/utils/profiling/canvasScheduler';
import {CanvasView} from 'sentry/utils/profiling/canvasView';
import {Flamegraph as FlamegraphModel} from 'sentry/utils/profiling/flamegraph';
import type {FlamegraphSearch as FlamegraphSearchType} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/reducers/flamegraphSearch';
import {useFlamegraphPreferences} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphPreferences';
import {useFlamegraphProfiles} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphProfiles';
import {useFlamegraphSearch} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphSearch';
import {useDispatchFlamegraphState} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphState';
import {useFlamegraphZoomPosition} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphZoomPosition';
import {useFlamegraphTheme} from 'sentry/utils/profiling/flamegraph/useFlamegraphTheme';
import {FlamegraphCanvas} from 'sentry/utils/profiling/flamegraphCanvas';
import type {ProfileSeriesMeasurement} from 'sentry/utils/profiling/flamegraphChart';
import {FlamegraphChart as FlamegraphChartModel} from 'sentry/utils/profiling/flamegraphChart';
import type {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame';
import {
computeConfigViewWithStrategy,
computeMinZoomConfigViewForFrames,
formatColorForFrame,
initializeFlamegraphRenderer,
useResizeCanvasObserver,
} from 'sentry/utils/profiling/gl/utils';
import type {ProfileGroup} from 'sentry/utils/profiling/profile/importProfile';
import {FlamegraphRenderer2D} from 'sentry/utils/profiling/renderers/flamegraphRenderer2D';
import {FlamegraphRendererWebGL} from 'sentry/utils/profiling/renderers/flamegraphRendererWebGL';
import type {SpanChartNode} from 'sentry/utils/profiling/spanChart';
import {SpanChart} from 'sentry/utils/profiling/spanChart';
import {SpanTree} from 'sentry/utils/profiling/spanTree';
import {Rect} from 'sentry/utils/profiling/speedscope';
import {UIFrames} from 'sentry/utils/profiling/uiFrames';
import type {ProfilingFormatterUnit} from 'sentry/utils/profiling/units/units';
import {formatTo, fromNanoJoulesToWatts} from 'sentry/utils/profiling/units/units';
import {useDevicePixelRatio} from 'sentry/utils/useDevicePixelRatio';
import {useMemoWithPrevious} from 'sentry/utils/useMemoWithPrevious';
import {useProfileGroup} from 'sentry/views/profiling/profileGroupProvider';
import {
useProfiles,
useProfileTransaction,
useSetProfiles,
} from 'sentry/views/profiling/profilesProvider';
import {FlamegraphDrawer} from './flamegraphDrawer/flamegraphDrawer';
import {FlamegraphWarnings} from './flamegraphOverlays/FlamegraphWarnings';
import {useViewKeyboardNavigation} from './interactions/useViewKeyboardNavigation';
import {FlamegraphChart} from './flamegraphChart';
import {FlamegraphLayout} from './flamegraphLayout';
import {FlamegraphSpans} from './flamegraphSpans';
import {FlamegraphUIFrames} from './flamegraphUIFrames';
function getMaxConfigSpace(
profileGroup: ProfileGroup,
transaction: EventTransaction | null,
unit: ProfilingFormatterUnit | string
): Rect {
// We have a transaction, so we should do our best to align the profile
// with the transaction's timeline.
const maxProfileDuration = Math.max(...profileGroup.profiles.map(p => p.duration));
if (transaction) {
// TODO: Adjust the alignment based on the profile's timestamp if it does
// not match the transaction's start timestamp
const transactionDuration = transaction.endTimestamp - transaction.startTimestamp;
// On most platforms, profile duration < transaction duration, however
// there is one beloved platform where that is not true; android.
// Hence, we should take the max of the two to ensure both the transaction
// and profile are fully visible to the user.
const duration = Math.max(
formatTo(transactionDuration, 'seconds', unit),
maxProfileDuration
);
return new Rect(0, 0, duration, 0);
}
// No transaction was found, so best we can do is align it to the starting
// position of the profiles - find the max of profile durations
return new Rect(0, 0, maxProfileDuration, 0);
}
function collectAllSpanEntriesFromTransaction(
transaction: EventTransaction
): EntrySpans['data'] {
if (!transaction.entries.length) {
return [];
}
const spans = transaction.entries.filter(
(e): e is EntrySpans => e.type === EntryType.SPANS
);
let allSpans: EntrySpans['data'] = [];
for (const span of spans) {
allSpans = allSpans.concat(span.data);
}
return allSpans;
}
type FlamegraphCandidate = {
frame: FlamegraphFrame;
threadId: number;
isActiveThread?: boolean; // this is the thread referred to by the active profile index
};
function findLongestMatchingFrame(
flamegraph: FlamegraphModel,
focusFrame: FlamegraphSearchType['highlightFrames']
): FlamegraphFrame | null {
if (focusFrame === null) {
return null;
}
let longestFrame: FlamegraphFrame | null = null;
const frames: FlamegraphFrame[] = [...flamegraph.root.children];
while (frames.length > 0) {
const frame = frames.pop()!;
if (
focusFrame.name === frame.frame.name &&
// the image name on a frame is optional treat it the same as the empty string
(focusFrame.package === (frame.frame.package || '') ||
focusFrame.package === (frame.frame.module || '')) &&
(longestFrame?.node?.totalWeight || 0) < frame.node.totalWeight
) {
longestFrame = frame;
}
for (let i = 0; i < frame.children.length; i++) {
frames.push(frame.children[i]);
}
}
return longestFrame;
}
function computeProfileOffset(
profileStart: string | undefined,
flamegraph: FlamegraphModel,
transaction: RequestState<EventTransaction | null>
): number {
let offset = flamegraph.profile.startedAt;
const transactionStart =
transaction.type === 'resolved' ? transaction.data?.startTimestamp ?? null : null;
if (
defined(transactionStart) &&
defined(profileStart) &&
// Android sometimes doesnt report timestamps, which end up being wrongly initialized when the data is ingested.
profileStart !== '0001-01-01T00:00:00Z'
) {
const profileStartTimestamp = new Date(profileStart).getTime() / 1e3;
const profileOffset = profileStartTimestamp - transactionStart;
offset += formatTo(profileOffset, 'second', flamegraph.profile.unit);
}
return offset;
}
const LOADING_OR_FALLBACK_FLAMEGRAPH = FlamegraphModel.Empty();
const LOADING_OR_FALLBACK_SPAN_TREE = SpanTree.Empty;
const LOADING_OR_FALLBACK_UIFRAMES = UIFrames.Empty;
const LOADING_OR_FALLBACK_BATTERY_CHART = FlamegraphChartModel.Empty;
const LOADING_OR_FALLBACK_CPU_CHART = FlamegraphChartModel.Empty;
const LOADING_OR_FALLBACK_MEMORY_CHART = FlamegraphChartModel.Empty;
const noopFormatDuration = () => '';
function Flamegraph(): ReactElement {
const devicePixelRatio = useDevicePixelRatio();
const profiledTransaction = useProfileTransaction();
const dispatch = useDispatchFlamegraphState();
const profiles = useProfiles();
const setProfiles = useSetProfiles();
const profileGroup = useProfileGroup();
const flamegraphTheme = useFlamegraphTheme();
const position = useFlamegraphZoomPosition();
const {colorCoding, sorting, view} = useFlamegraphPreferences();
const {highlightFrames} = useFlamegraphSearch();
const flamegraphProfiles = useFlamegraphProfiles();
const [flamegraphCanvasRef, setFlamegraphCanvasRef] =
useState<HTMLCanvasElement | null>(null);
const [flamegraphOverlayCanvasRef, setFlamegraphOverlayCanvasRef] =
useState<HTMLCanvasElement | null>(null);
const [flamegraphMiniMapCanvasRef, setFlamegraphMiniMapCanvasRef] =
useState<HTMLCanvasElement | null>(null);
const [flamegraphMiniMapOverlayCanvasRef, setFlamegraphMiniMapOverlayCanvasRef] =
useState<HTMLCanvasElement | null>(null);
const [spansCanvasRef, setSpansCanvasRef] = useState<HTMLCanvasElement | null>(null);
const [uiFramesCanvasRef, setUIFramesCanvasRef] = useState<HTMLCanvasElement | null>(
null
);
const [batteryChartCanvasRef, setBatteryChartCanvasRef] =
useState<HTMLCanvasElement | null>(null);
const [cpuChartCanvasRef, setCpuChartCanvasRef] = useState<HTMLCanvasElement | null>(
null
);
const [memoryChartCanvasRef, setMemoryChartCanvasRef] =
useState<HTMLCanvasElement | null>(null);
const canvasPoolManager = useMemo(() => new CanvasPoolManager(), []);
const scheduler = useCanvasScheduler(canvasPoolManager);
const hasUIFrames = useMemo(() => {
const platform = profileGroup.metadata.platform;
return platform === 'cocoa' || platform === 'android';
}, [profileGroup.metadata.platform]);
const hasBatteryChart = useMemo(() => {
const platform = profileGroup.metadata.platform;
return platform === 'cocoa' || profileGroup.measurements?.cpu_energy_usage;
}, [profileGroup.metadata.platform, profileGroup.measurements]);
const hasCPUChart = useMemo(() => {
const platform = profileGroup.metadata.platform;
return (
platform === 'cocoa' ||
platform === 'android' ||
platform === 'node' ||
profileGroup.measurements?.cpu_usage
);
}, [profileGroup.metadata.platform, profileGroup.measurements]);
const hasMemoryChart = useMemo(() => {
const platform = profileGroup.metadata.platform;
return (
platform === 'cocoa' ||
platform === 'android' ||
platform === 'node' ||
profileGroup.measurements?.memory_footprint
);
}, [profileGroup.metadata.platform, profileGroup.measurements]);
const profile = useMemo(() => {
return profileGroup.profiles.find(p => p.threadId === flamegraphProfiles.threadId);
}, [profileGroup, flamegraphProfiles.threadId]);
const spanTree: SpanTree = useMemo(() => {
if (profiledTransaction.type === 'resolved' && profiledTransaction.data) {
return new SpanTree(
profiledTransaction.data,
collectAllSpanEntriesFromTransaction(profiledTransaction.data)
);
}
return LOADING_OR_FALLBACK_SPAN_TREE;
}, [profiledTransaction]);
const spanChart = useMemo(() => {
if (!profile) {
return null;
}
return new SpanChart(spanTree, {
unit: profile.unit,
configSpace: getMaxConfigSpace(
profileGroup,
profiledTransaction.type === 'resolved' ? profiledTransaction.data : null,
profile.unit
),
});
}, [spanTree, profile, profileGroup, profiledTransaction]);
const flamegraph = useMemo(() => {
if (typeof flamegraphProfiles.threadId !== 'number') {
return LOADING_OR_FALLBACK_FLAMEGRAPH;
}
// This could happen if threadId was initialized from query string, but for some
// reason the profile was removed from the list of profiles.
if (!profile) {
return LOADING_OR_FALLBACK_FLAMEGRAPH;
}
// Wait for the transaction to finish loading, regardless of the results.
// Otherwise, the rendered profile will probably shift once the transaction loads.
if (
profiledTransaction.type === 'loading' ||
profiledTransaction.type === 'initial'
) {
return LOADING_OR_FALLBACK_FLAMEGRAPH;
}
const span = Sentry.withScope(scope => {
scope.setTag('sorting', sorting.split(' ').join('_'));
scope.setTag('view', view.split(' ').join('_'));
return Sentry.startInactiveSpan({
op: 'import',
name: 'flamegraph.constructor',
forceTransaction: true,
});
});
const newFlamegraph = new FlamegraphModel(profile, {
inverted: view === 'bottom up',
sort: sorting,
configSpace: getMaxConfigSpace(
profileGroup,
profiledTransaction.type === 'resolved' ? profiledTransaction.data : null,
profile.unit
),
});
span?.end();
return newFlamegraph;
}, [
profile,
profileGroup,
profiledTransaction,
sorting,
flamegraphProfiles.threadId,
view,
]);
const profileOffsetFromTransaction = useMemo(
() =>
computeProfileOffset(
profileGroup.metadata.timestamp,
flamegraph,
profiledTransaction
),
[flamegraph, profiledTransaction, profileGroup.metadata.timestamp]
);
const uiFrames = useMemo(() => {
if (!hasUIFrames) {
return LOADING_OR_FALLBACK_UIFRAMES;
}
return new UIFrames(
{
slow: profileGroup.measurements?.slow_frame_renders,
frozen: profileGroup.measurements?.frozen_frame_renders,
},
{unit: flamegraph.profile.unit},
flamegraph.configSpace.withHeight(1)
);
}, [
profileGroup.measurements,
flamegraph.profile.unit,
flamegraph.configSpace,
hasUIFrames,
]);
const batteryChart = useMemo(() => {
if (!hasCPUChart) {
return LOADING_OR_FALLBACK_BATTERY_CHART;
}
const measures: ProfileSeriesMeasurement[] = [];
for (const key in profileGroup.measurements) {
if (key === 'cpu_energy_usage') {
measures.push({
...profileGroup.measurements[key]!,
values: profileGroup.measurements[key]!.values.map(v => {
return {
elapsed_since_start_ns: v.elapsed_since_start_ns,
value: fromNanoJoulesToWatts(v.value, 0.1),
};
}),
// some versions of cocoa send byte so we need to correct it to watt
unit: 'watt',
name: 'CPU energy usage',
});
}
}
return new FlamegraphChartModel(
Rect.From(flamegraph.configSpace),
measures.length > 0 ? measures : [],
flamegraphTheme.COLORS.BATTERY_CHART_COLORS
);
}, [profileGroup.measurements, flamegraph.configSpace, flamegraphTheme, hasCPUChart]);
const CPUChart = useMemo(() => {
if (!hasCPUChart) {
return LOADING_OR_FALLBACK_CPU_CHART;
}
const measures: ProfileSeriesMeasurement[] = [];
for (const key in profileGroup.measurements) {
if (key.startsWith('cpu_usage')) {
const name =
key === 'cpu_usage'
? 'Average CPU usage'
: `CPU Core ${key.replace('cpu_usage_', '')}`;
measures.push({...profileGroup.measurements[key]!, name});
}
}
return new FlamegraphChartModel(
Rect.From(flamegraph.configSpace),
measures.length > 0 ? measures : [],
flamegraphTheme.COLORS.CPU_CHART_COLORS
);
}, [profileGroup.measurements, flamegraph.configSpace, flamegraphTheme, hasCPUChart]);
const memoryChart = useMemo(() => {
if (!hasMemoryChart) {
return LOADING_OR_FALLBACK_MEMORY_CHART;
}
const measures: ProfileSeriesMeasurement[] = [];
const memory_footprint = profileGroup.measurements?.memory_footprint;
if (memory_footprint) {
measures.push({
...memory_footprint!,
name: 'Heap Usage',
});
}
const native_memory_footprint = profileGroup.measurements?.memory_native_footprint;
if (native_memory_footprint) {
measures.push({
...native_memory_footprint!,
name: 'Native Heap Usage',
});
}
return new FlamegraphChartModel(
Rect.From(flamegraph.configSpace),
measures.length > 0 ? measures : [],
flamegraphTheme.COLORS.MEMORY_CHART_COLORS,
{type: 'area'}
);
}, [
profileGroup.measurements,
flamegraph.configSpace,
flamegraphTheme,
hasMemoryChart,
]);
const flamegraphCanvas = useMemo(() => {
if (!flamegraphCanvasRef) {
return null;
}
return new FlamegraphCanvas(
flamegraphCanvasRef,
vec2.fromValues(0, flamegraphTheme.SIZES.TIMELINE_HEIGHT * devicePixelRatio)
);
}, [devicePixelRatio, flamegraphCanvasRef, flamegraphTheme]);
const flamegraphMiniMapCanvas = useMemo(() => {
if (!flamegraphMiniMapCanvasRef) {
return null;
}
return new FlamegraphCanvas(flamegraphMiniMapCanvasRef, vec2.fromValues(0, 0));
}, [flamegraphMiniMapCanvasRef]);
const spansCanvas = useMemo(() => {
if (!spansCanvasRef) {
return null;
}
return new FlamegraphCanvas(spansCanvasRef, vec2.fromValues(0, 0));
}, [spansCanvasRef]);
const uiFramesCanvas = useMemo(() => {
if (!uiFramesCanvasRef) {
return null;
}
return new FlamegraphCanvas(uiFramesCanvasRef, vec2.fromValues(0, 0));
}, [uiFramesCanvasRef]);
const batteryChartCanvas = useMemo(() => {
if (!batteryChartCanvasRef) {
return null;
}
return new FlamegraphCanvas(batteryChartCanvasRef, vec2.fromValues(0, 0));
}, [batteryChartCanvasRef]);
const cpuChartCanvas = useMemo(() => {
if (!cpuChartCanvasRef) {
return null;
}
return new FlamegraphCanvas(cpuChartCanvasRef, vec2.fromValues(0, 0));
}, [cpuChartCanvasRef]);
const memoryChartCanvas = useMemo(() => {
if (!memoryChartCanvasRef) {
return null;
}
return new FlamegraphCanvas(memoryChartCanvasRef, vec2.fromValues(0, 0));
}, [memoryChartCanvasRef]);
const flamegraphView = useMemoWithPrevious<CanvasView<FlamegraphModel> | null>(
previousView => {
if (!flamegraphCanvas) {
return null;
}
const newView = new CanvasView({
canvas: flamegraphCanvas,
model: flamegraph,
options: {
inverted: flamegraph.inverted,
minWidth: flamegraph.profile.minFrameDuration,
barHeight: flamegraphTheme.SIZES.BAR_HEIGHT,
depthOffset: flamegraphTheme.SIZES.FLAMEGRAPH_DEPTH_OFFSET,
configSpaceTransform: new Rect(profileOffsetFromTransaction, 0, 0, 0),
},
});
if (
// if the profile or the config space of the flamegraph has changed, we do not
// want to persist the config view. This is to avoid a case where the new config space
// is larger than the previous one, meaning the new view could now be zoomed in even
// though the user did not fire any zoom events.
previousView?.model.profile === newView.model.profile &&
previousView.configSpace.equals(newView.configSpace)
) {
if (
// if we're still looking at the same profile but only a preference other than
// left heavy has changed, we do want to persist the config view
previousView.model.sort === 'left heavy' &&
newView.model.sort === 'left heavy'
) {
newView.setConfigView(
previousView.configView.withHeight(newView.configView.height)
);
}
}
if (defined(highlightFrames)) {
let frames = flamegraph.findAllMatchingFrames(
highlightFrames.name,
highlightFrames.package
);
if (
!frames.length &&
!highlightFrames.package &&
highlightFrames.name &&
profileGroup.metadata.platform === 'node'
) {
// there is a chance that the reason we did not find any frames is because
// for node, we try to infer some package from the frontend code.
// If that happens, we'll try and just do a search by name. This logic
// is duplicated in flamegraphZoomView.tsx and should be kept in sync
frames = flamegraph.findAllMatchingFramesBy(highlightFrames.name, ['name']);
}
if (frames.length > 0) {
const rectFrames = frames.map(
f => new Rect(f.start, f.depth, f.end - f.start, 1)
);
const newConfigView = computeMinZoomConfigViewForFrames(
newView.configView,
rectFrames
).transformRect(newView.configSpaceTransform);
newView.setConfigView(newConfigView);
return newView;
}
}
// Because we render empty flamechart while we fetch the data, we need to make sure
// to have some heuristic when the data is fetched to determine if we should
// initialize the config view to the full view or a predefined value
else if (
!defined(highlightFrames) &&
position.view &&
!position.view.isEmpty() &&
previousView?.model === LOADING_OR_FALLBACK_FLAMEGRAPH
) {
// We allow min width to be initialize to lower than view.minWidth because
// there is a chance that user zoomed into a span duration which may have been updated
// after the model was loaded (see L320)
newView.setConfigView(position.view, {width: {min: 0}});
}
return newView;
},
// We skip position.view dependency because it will go into an infinite loop
// eslint-disable-next-line react-hooks/exhaustive-deps
[flamegraph, flamegraphCanvas, flamegraphTheme, profileOffsetFromTransaction]
);
const uiFramesView = useMemoWithPrevious<CanvasView<UIFrames> | null>(
_previousView => {
if (!flamegraphView || !flamegraphCanvas || !uiFrames) {
return null;
}
const newView = new CanvasView({
canvas: flamegraphCanvas,
model: uiFrames,
mode: 'stretchToFit',
options: {
inverted: flamegraph.inverted,
minWidth: uiFrames.minFrameDuration,
barHeight: 10,
depthOffset: 0,
configSpaceTransform: new Rect(profileOffsetFromTransaction, 0, 0, 0),
},
});
// Initialize configView to whatever the flamegraph configView is
newView.setConfigView(
flamegraphView.configView.withHeight(newView.configView.height),
{width: {min: 0}}
);
return newView;
},
[flamegraphView, flamegraphCanvas, flamegraph, uiFrames, profileOffsetFromTransaction]
);
const batteryChartView = useMemoWithPrevious<CanvasView<FlamegraphChartModel> | null>(
_previousView => {
if (!flamegraphView || !flamegraphCanvas || !batteryChart || !batteryChartCanvas) {
return null;
}
const newView = new CanvasView({
canvas: flamegraphCanvas,
model: batteryChart,
mode: 'anchorBottom',
options: {
// Invert chart so origin is at bottom left
// corner as opposed to top left
inverted: true,
minWidth: uiFrames.minFrameDuration,
barHeight: 0,
depthOffset: 0,
maxHeight: batteryChart.configSpace.height,
minHeight: batteryChart.configSpace.height,
configSpaceTransform: new Rect(profileOffsetFromTransaction, 0, 0, 0),
},
});
// Compute the total size of the padding and stretch the view. This ensures that
// the total range is rendered and perfectly aligned from top to bottom.
newView.setConfigView(
flamegraphView.configView.withHeight(newView.configView.height),
{
width: {min: 1},
}
);
return newView;
},
[
flamegraphView,
flamegraphCanvas,
batteryChart,
uiFrames.minFrameDuration,
batteryChartCanvas,
profileOffsetFromTransaction,
]
);
const cpuChartView = useMemoWithPrevious<CanvasView<FlamegraphChartModel> | null>(
_previousView => {
if (!flamegraphView || !flamegraphCanvas || !CPUChart || !cpuChartCanvas) {
return null;
}
const newView = new CanvasView({
canvas: flamegraphCanvas,
model: CPUChart,
mode: 'anchorBottom',
options: {
// Invert chart so origin is at bottom left
// corner as opposed to top left
inverted: true,
minWidth: uiFrames.minFrameDuration,
barHeight: 0,
depthOffset: 0,
maxHeight: CPUChart.configSpace.height,
minHeight: CPUChart.configSpace.height,
configSpaceTransform: new Rect(profileOffsetFromTransaction, 0, 0, 0),
},
});
// Compute the total size of the padding and stretch the view. This ensures that
// the total range is rendered and perfectly aligned from top to bottom.
newView.setConfigView(
flamegraphView.configView.withHeight(newView.configView.height),
{
width: {min: 1},
}
);
return newView;
},
[
flamegraphView,
flamegraphCanvas,
CPUChart,
uiFrames.minFrameDuration,
cpuChartCanvas,
profileOffsetFromTransaction,
]
);
const memoryChartView = useMemoWithPrevious<CanvasView<FlamegraphChartModel> | null>(
_previousView => {
if (!flamegraphView || !flamegraphCanvas || !memoryChart || !memoryChartCanvas) {
return null;
}
const newView = new CanvasView({
canvas: flamegraphCanvas,
model: memoryChart,
mode: 'anchorBottom',
options: {
// Invert chart so origin is at bottom left
// corner as opposed to top left
inverted: true,
minWidth: uiFrames.minFrameDuration,
barHeight: 0,
depthOffset: 0,
maxHeight: memoryChart.configSpace.height,
minHeight: memoryChart.configSpace.height,
configSpaceTransform: new Rect(profileOffsetFromTransaction, 0, 0, 0),
},
});
// Compute the total size of the padding and stretch the view. This ensures that
// the total range is rendered and perfectly aligned from top to bottom.
newView.setConfigView(
flamegraphView.configView.withHeight(newView.configView.height),
{
width: {min: 1},
}
);
return newView;
},
[
flamegraphView,
flamegraphCanvas,
memoryChart,
uiFrames.minFrameDuration,
memoryChartCanvas,
profileOffsetFromTransaction,
]
);
const spansView = useMemoWithPrevious<CanvasView<SpanChart> | null>(
_previousView => {
if (!spansCanvas || !spanChart || !flamegraphView) {
return null;
}
const newView = new CanvasView({
canvas: spansCanvas,
model: spanChart,
options: {
inverted: false,
minWidth: spanChart.minSpanDuration,
barHeight: flamegraphTheme.SIZES.SPANS_BAR_HEIGHT,
depthOffset: flamegraphTheme.SIZES.SPANS_DEPTH_OFFSET,
},
});
// Initialize configView to whatever the flamegraph configView is
newView.setConfigView(
flamegraphView.configView.withHeight(newView.configView.height),
{width: {min: 1}}
);
return newView;
},
[spanChart, spansCanvas, flamegraphView, flamegraphTheme.SIZES]
);
// We want to make sure that the views have the same min zoom levels so that
// if you wheel zoom on one, the other one will also zoom to the same level of detail.
// If we dont do this, then at some point during the zoom action the views will
// detach and only one will zoom while the other one will stay at the same zoom level.
useEffect(() => {
const minWidthBetweenViews = Math.min(
flamegraphView?.minWidth ?? Number.MAX_SAFE_INTEGER,
spansView?.minWidth ?? Number.MAX_SAFE_INTEGER,
uiFramesView?.minWidth ?? Number.MAX_SAFE_INTEGER,
cpuChartView?.minWidth ?? Number.MAX_SAFE_INTEGER,
memoryChartView?.minWidth ?? Number.MAX_SAFE_INTEGER,
batteryChartView?.minWidth ?? Number.MAX_SAFE_INTEGER
);
flamegraphView?.setMinWidth?.(minWidthBetweenViews);
spansView?.setMinWidth?.(minWidthBetweenViews);
uiFramesView?.setMinWidth?.(minWidthBetweenViews);
cpuChartView?.setMinWidth?.(minWidthBetweenViews);
memoryChartView?.setMinWidth?.(minWidthBetweenViews);
batteryChartView?.setMinWidth?.(minWidthBetweenViews);
}, [
flamegraphView,
spansView,
uiFramesView,
cpuChartView,
memoryChartView,
batteryChartView,
]);
// Uses a useLayoutEffect to ensure that these top level/global listeners are added before
// any of the children components effects actually run. This way we do not lose events
// when we register/unregister these top level listeners.
useLayoutEffect(() => {
if (!flamegraphCanvas || !flamegraphView) {
return undefined;
}
// This code below manages the synchronization of the config views between spans and flamegraph
// We do so by listening to the config view change event and then updating the other views accordingly which
// allows us to keep the X axis in sync between the two views but keep the Y axis independent
const onConfigViewChange = (rect: Rect, sourceConfigViewChange: CanvasView<any>) => {
if (sourceConfigViewChange === flamegraphView) {
flamegraphView.setConfigView(rect.withHeight(flamegraphView.configView.height));
if (spansView) {
const beforeY = spansView.configView.y;
spansView.setConfigView(
rect.withHeight(spansView.configView.height).withY(beforeY)
);
}
if (uiFramesView) {
uiFramesView.setConfigView(rect);
}
if (cpuChartView) {
cpuChartView.setConfigView(rect);
}
if (memoryChartView) {
memoryChartView.setConfigView(rect);
}
if (batteryChartView) {
batteryChartView.setConfigView(rect);
}
}
if (sourceConfigViewChange === spansView) {
spansView.setConfigView(rect.withHeight(spansView.configView.height));
const beforeY = flamegraphView.configView.y;
flamegraphView.setConfigView(
rect.withHeight(flamegraphView.configView.height).withY(beforeY)
);
if (uiFramesView) {
uiFramesView.setConfigView(rect);
}
if (cpuChartView) {
cpuChartView.setConfigView(rect);
}
if (memoryChartView) {
memoryChartView.setConfigView(rect);
}
if (batteryChartView) {
batteryChartView.setConfigView(rect);
}
}
canvasPoolManager.draw();
};
const onTransformConfigView = (
mat: mat3,
sourceTransformConfigView: CanvasView<any>
) => {
if (sourceTransformConfigView === flamegraphView) {
flamegraphView.transformConfigView(mat);
if (spansView) {
const beforeY = spansView.configView.y;
spansView.transformConfigView(mat);
spansView.setConfigView(spansView.configView.withY(beforeY));
}
if (uiFramesView) {
uiFramesView.transformConfigView(mat);
}
if (batteryChartView) {
batteryChartView.transformConfigView(mat);
}
if (cpuChartView) {
cpuChartView.transformConfigView(mat);
}
if (memoryChartView) {
memoryChartView.transformConfigView(mat);
}
}
if (sourceTransformConfigView === spansView) {
spansView.transformConfigView(mat);
const beforeY = flamegraphView.configView.y;
flamegraphView.transformConfigView(mat);
flamegraphView.setConfigView(flamegraphView.configView.withY(beforeY));
if (uiFramesView) {
uiFramesView.transformConfigView(mat);
}
if (batteryChartView) {
batteryChartView.transformConfigView(mat);
}
if (cpuChartView) {
cpuChartView.transformConfigView(mat);
}
if (memoryChartView) {
memoryChartView.transformConfigView(mat);
}
}
if (
sourceTransformConfigView === uiFramesView ||
sourceTransformConfigView === cpuChartView ||
sourceTransformConfigView === memoryChartView ||
sourceTransformConfigView === batteryChartView
) {
if (flamegraphView) {
const beforeY = flamegraphView.configView.y;
flamegraphView.transformConfigView(mat);
flamegraphView.setConfigView(flamegraphView.configView.withY(beforeY));
}
if (spansView) {
const beforeY = spansView.configView.y;
spansView.transformConfigView(mat);
spansView.setConfigView(spansView.configView.withY(beforeY));
}
if (uiFramesView) {
uiFramesView.transformConfigView(mat);
}
if (batteryChartView) {
batteryChartView.transformConfigView(mat);
}
if (cpuChartView) {
cpuChartView.transformConfigView(mat);
}
if (memoryChartView) {
memoryChartView.transformConfigView(mat);
}
}
canvasPoolManager.draw();
};
const onResetZoom = () => {
flamegraphView.resetConfigView(flamegraphCanvas);
if (spansView && spansCanvas) {
spansView.resetConfigView(spansCanvas);
}
if (uiFramesView && uiFramesCanvas) {
uiFramesView.resetConfigView(uiFramesCanvas);
}
if (batteryChartView && batteryChartCanvas) {
batteryChartView.resetConfigView(batteryChartCanvas);
}
if (cpuChartView && cpuChartCanvas) {
cpuChartView.resetConfigView(cpuChartCanvas);
}
if (memoryChartView && memoryChartCanvas) {
memoryChartView.resetConfigView(memoryChartCanvas);
}
canvasPoolManager.draw();
};
const onZoomIntoFrame = (frame: FlamegraphFrame, strategy: 'min' | 'exact') => {
const newConfigView = computeConfigViewWithStrategy(
strategy,
flamegraphView.configView,
new Rect(frame.start, frame.depth, frame.end - frame.start, 1)
).transformRect(flamegraphView.configSpaceTransform);
flamegraphView.setConfigView(newConfigView);
if (spansView) {