forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracks.js
1669 lines (1516 loc) · 53 KB
/
tracks.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
/* 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 type {
ScreenshotPayload,
Profile,
Thread,
ThreadIndex,
Pid,
GlobalTrack,
LocalTrack,
TrackIndex,
Counter,
Tid,
TrackReference,
MarkerSchemaByName,
TabID,
} from 'firefox-profiler/types';
import { defaultThreadOrder, getFriendlyThreadName } from './profile-data';
import { intersectSets, subtractSets } from '../utils/set';
import { splitSearchString, stringsToRegExp } from '../utils/string';
import { ensureExists, assertExhaustiveCheck } from '../utils/flow';
import { getMarkerSchemaName } from './marker-schema';
export type TracksWithOrder = {|
+globalTracks: GlobalTrack[],
+globalTrackOrder: TrackIndex[],
+localTracksByPid: Map<Pid, LocalTrack[]>,
+localTrackOrderByPid: Map<Pid, TrackIndex[]>,
|};
export type HiddenTracks = {|
+hiddenGlobalTracks: Set<TrackIndex>,
+hiddenLocalTracksByPid: Map<Pid, Set<TrackIndex>>,
|};
/**
* This file collects all the logic that goes into validating URL-encoded view options.
* It also selects the default view options for things like track hiding, ordering,
* and selection.
*/
/**
* In order for track indexes to be backwards compatible, the indexes need to be
* stable across time. Therefore the tracks must be consistently sorted. When new
* track types are added, they must be added to the END of the track list, so that
* URL-encoded information remains stable.
*
* However, this sorting may not be the one we want to display to the end user, so provide
* a secondary sorting order for how the tracks will actually be displayed.
*/
const LOCAL_TRACK_INDEX_ORDER = {
thread: 0,
network: 1,
memory: 2,
ipc: 3,
'event-delay': 4,
'process-cpu': 5,
power: 6,
marker: 7,
bandwidth: 8,
};
const LOCAL_TRACK_DISPLAY_ORDER = {
network: 0,
bandwidth: 1,
memory: 2,
power: 3,
// IPC tracks that belong to the global track will appear right after network
// and counter tracks. But we want to show the IPC tracks that belong to the
// local threads right after their track. This special handling happens inside
// the sort function.
ipc: 4,
thread: 5,
'event-delay': 6,
'process-cpu': 7,
marker: 8,
};
const GLOBAL_TRACK_INDEX_ORDER = {
process: 0,
screenshots: 1,
'visual-progress': 2,
'perceptual-visual-progress': 3,
'contentful-visual-progress': 4,
};
const GLOBAL_TRACK_DISPLAY_ORDER = {
'visual-progress': 0,
'perceptual-visual-progress': 1,
'contentful-visual-progress': 2,
screenshots: 3,
process: 4,
};
function _getDefaultLocalTrackOrder(tracks: LocalTrack[], profile: ?Profile) {
const trackOrder = tracks.map((_, index) => index);
const naturalSort = new Intl.Collator('en-US', { numeric: true });
// In place sort!
trackOrder.sort((a, b) => {
if (
tracks[a].type === 'thread' &&
tracks[b].type === 'ipc' &&
tracks[a].threadIndex === tracks[b].threadIndex
) {
// If the IPC track belongs to that local thread, put the IPC tracks right
// after it.
return -1;
}
if (
tracks[a].type === 'ipc' &&
tracks[b].type === 'thread' &&
tracks[a].threadIndex === tracks[b].threadIndex
) {
// If the IPC track belongs to that local thread, put the IPC tracks right
// after it.
return 1;
}
if (
profile &&
profile.counters &&
tracks[a].type === 'power' &&
tracks[b].type === 'power'
) {
const idxA = tracks[a].counterIndex;
const idxB = tracks[b].counterIndex;
if (profile.meta.keepProfileThreadOrder) {
return idxA - idxB;
}
const nameA = profile.counters[idxA].name;
const nameB = profile.counters[idxB].name;
return naturalSort.compare(nameA, nameB);
}
// If the tracks are both threads, sort them by thread name, and then by
// creation time if they have the same name.
if (tracks[a].type === 'thread' && tracks[b].type === 'thread' && profile) {
const idxA = tracks[a].threadIndex;
const idxB = tracks[b].threadIndex;
if (idxA === undefined || idxB === undefined) {
return -1;
}
if (profile && profile.meta.keepProfileThreadOrder) {
return idxA - idxB;
}
const nameA = profile.threads[idxA].name;
const nameB = profile.threads[idxB].name;
return (
naturalSort.compare(nameA, nameB) ||
profile.threads[idxA].registerTime - profile.threads[idxB].registerTime
);
}
return (
LOCAL_TRACK_DISPLAY_ORDER[tracks[a].type] -
LOCAL_TRACK_DISPLAY_ORDER[tracks[b].type]
);
});
return trackOrder;
}
function _getDefaultGlobalTrackOrder(tracks: GlobalTrack[]) {
const trackOrder = tracks.map((_, index) => index);
// In place sort!
trackOrder.sort(
(a, b) =>
GLOBAL_TRACK_DISPLAY_ORDER[tracks[a].type] -
GLOBAL_TRACK_DISPLAY_ORDER[tracks[b].type]
);
return trackOrder;
}
/**
* Determine the display order of the local tracks. This will be a different order than
* how the local tracks are stored, as the initial ordering must be stable when new
* track types are added.
*/
export function initializeLocalTrackOrderByPid(
// If viewing an existing profile, take the track ordering from the URL and sanitize it.
urlTrackOrderByPid: Map<Pid, TrackIndex[]> | null,
// This is the list of the tracks.
localTracksByPid: Map<Pid, LocalTrack[]>,
// If viewing an old profile URL, there were not tracks, only thread indexes. Turn
// the legacy ordering into track ordering.
legacyThreadOrder: ThreadIndex[] | null,
profile: ?Profile
): Map<Pid, TrackIndex[]> {
const trackOrderByPid = new Map();
if (legacyThreadOrder === null) {
// Go through each set of tracks, determine the sort order.
for (const [pid, tracks] of localTracksByPid) {
// Create the default trackOrder.
let trackOrder = _getDefaultLocalTrackOrder(tracks, profile);
if (urlTrackOrderByPid !== null) {
// Sanitize the track information provided by the URL, and ensure it is valid.
let urlTrackOrder = urlTrackOrderByPid.get(pid);
if (urlTrackOrder !== undefined) {
// A URL track order was found, sanitize it.
if (urlTrackOrder.length !== trackOrder.length) {
// The URL track order length doesn't match the tracks we've generated. Most
// likely this means that we have generated new tracks that the URL does not
// know about. Add indexes at the end for the new tracks. These new indexes
// will still be checked by the _indexesAreValid function below.
const newOrder = urlTrackOrder.slice();
for (let i = urlTrackOrder.length; i < trackOrder.length; i++) {
newOrder.push(i);
}
urlTrackOrder = newOrder;
}
if (_indexesAreValid(tracks.length, urlTrackOrder)) {
trackOrder = urlTrackOrder;
}
}
}
trackOrderByPid.set(pid, trackOrder);
}
} else {
// Convert the legacy thread order into the current track order.
for (const [pid, tracks] of localTracksByPid) {
const trackOrder = [];
// Go through the legacy thread order and pair it with the correct track.
for (const threadIndex of legacyThreadOrder) {
const trackIndex = tracks.findIndex(
(track) =>
track.type === 'thread' && track.threadIndex === threadIndex
);
if (trackIndex !== -1) {
trackOrder.push(trackIndex);
}
}
// Complete the list of track indexes by adding them to the end.
for (let trackIndex = 0; trackIndex < tracks.length; trackIndex++) {
if (!trackOrder.includes(trackIndex)) {
trackOrder.push(trackIndex);
}
}
trackOrderByPid.set(pid, trackOrder);
}
}
return trackOrderByPid;
}
/**
* Take a profile and figure out all of the local tracks, and organize them by PID.
* availableGlobalTracks is being sent by the caller to see which globalTracks
* are present. The ones that have been filtered out by the tab selector
* should be ignored.
*/
export function computeLocalTracksByPid(
profile: Profile,
availableGlobalTracks: GlobalTrack[],
markerSchemaByName: MarkerSchemaByName
): Map<Pid, LocalTrack[]> {
const localTracksByPid = new Map();
// Create a new set of available pids, so we can filter out the local tracks
// if their globalTracks are also filtered out by the tab selector.
const availablePids = new Set();
for (const globalTrack of availableGlobalTracks) {
if (globalTrack.type === 'process') {
availablePids.add(globalTrack.pid);
}
}
// find markers that might have their own track.
const markerSchemasWithGraphs = (profile.meta.markerSchema || []).filter(
(schema) => Array.isArray(schema.graphs) && schema.graphs.length > 0
);
for (
let threadIndex = 0;
threadIndex < profile.threads.length;
threadIndex++
) {
const thread = profile.threads[threadIndex];
const { pid, markers } = thread;
if (!availablePids.has(pid)) {
// If the global track is filtered out ignore it here too.
continue;
}
// Get or create the tracks and trackOrder.
let tracks = localTracksByPid.get(pid);
if (tracks === undefined) {
tracks = [];
localTracksByPid.set(pid, tracks);
}
if (!thread.isMainThread) {
// This thread has not been added as a GlobalTrack, so add it as a local track.
tracks.push({ type: 'thread', threadIndex });
}
if (markers.data.some((datum) => datum && datum.type === 'Network')) {
// This thread has network markers.
tracks.push({ type: 'network', threadIndex });
}
if (markers.data.some((datum) => datum && datum.type === 'IPC')) {
// This thread has IPC markers.
tracks.push({ type: 'ipc', threadIndex });
}
if (markerSchemasWithGraphs.length > 0) {
const markerTracksBySchemaName = new Map();
for (const markerSchema of markerSchemasWithGraphs) {
markerTracksBySchemaName.set(markerSchema.name, {
markerSchema,
keys: (markerSchema.graphs || []).map((graph) => graph.key),
markerNames: new Set(),
});
}
for (let i = 0; i < markers.length; ++i) {
const markerNameIndex = markers.name[i];
const markerData = markers.data[i];
const markerSchemaName = getMarkerSchemaName(
markerSchemaByName,
thread.stringTable.getString(markerNameIndex),
markerData
);
if (markerData && markerSchemaByName) {
const mapEntry = markerTracksBySchemaName.get(markerSchemaName);
if (mapEntry && mapEntry.keys.every((k) => k in markerData)) {
mapEntry.markerNames.add(markerNameIndex);
}
}
}
for (const [
,
{ markerSchema, markerNames },
] of markerTracksBySchemaName) {
for (const markerName of markerNames) {
tracks.push({
type: 'marker',
threadIndex,
markerSchema,
markerName,
});
}
}
}
}
const { counters } = profile;
if (counters) {
for (let counterIndex = 0; counterIndex < counters.length; counterIndex++) {
const { pid, category, samples } = counters[counterIndex];
if (!availablePids.has(pid)) {
// If the global track is filtered out ignore it here too.
continue;
}
if (['Memory', 'power', 'Bandwidth'].includes(category)) {
if (category === 'power' && samples.length <= 2) {
// If we have only 2 samples, they are likely both 0 and we don't have a real counter.
continue;
}
let tracks = localTracksByPid.get(pid);
if (tracks === undefined) {
tracks = [];
localTracksByPid.set(pid, tracks);
}
if (category === 'Memory') {
tracks.push({ type: 'memory', counterIndex });
} else if (category === 'Bandwidth') {
tracks.push({ type: 'bandwidth', counterIndex });
} else {
tracks.push({ type: 'power', counterIndex });
}
}
}
}
// When adding a new track type, this for loop ensures that the newer tracks are
// added at the end so that the local track indexes are stable and backwards compatible.
for (const localTracks of localTracksByPid.values()) {
// In place sort!
localTracks.sort(
(a, b) =>
LOCAL_TRACK_INDEX_ORDER[a.type] - LOCAL_TRACK_INDEX_ORDER[b.type]
);
}
return localTracksByPid;
}
/**
* Take threads and add event delay tracks for them. Return the new
* localTracksByPid map.
*/
export function addEventDelayTracksForThreads(
threads: Thread[],
localTracksByPid: Map<Pid, LocalTrack[]>
): Map<Pid, LocalTrack[]> {
const newLocalTracksByPid = new Map();
for (let threadIndex = 0; threadIndex < threads.length; threadIndex++) {
const thread = threads[threadIndex];
const { pid } = thread;
// Get or create the tracks and trackOrder.
let tracks = newLocalTracksByPid.get(pid);
if (tracks === undefined) {
tracks = localTracksByPid.get(pid);
if (tracks === undefined) {
tracks = [];
}
// copy it so we don't mutate the state
tracks = [...tracks];
}
tracks.push({ type: 'event-delay', threadIndex });
newLocalTracksByPid.set(pid, tracks);
}
return newLocalTracksByPid;
}
/**
* Take global tracks and add the experimental process CPU tracks. Return the new
* localTracksByPid map.
*/
export function addProcessCPUTracksForProcess(
counters: Counter[] | null,
localTracksByPid: Map<Pid, LocalTrack[]>
): Map<Pid, LocalTrack[]> {
if (counters === null) {
// We don't have any counters to add.
return localTracksByPid;
}
const newLocalTracksByPid = new Map(localTracksByPid);
for (const [counterIndex, counter] of counters.entries()) {
if (counter.category !== 'CPU' || counter.name !== 'processCPU') {
// We only care about the process CPU counter types.
continue;
}
const { pid } = counter;
let localTracks = newLocalTracksByPid.get(pid) ?? [];
// Do not mutate the current state.
localTracks = [...localTracks, { type: 'process-cpu', counterIndex }];
newLocalTracksByPid.set(pid, localTracks);
}
return newLocalTracksByPid;
}
/**
* Take a profile and figure out what GlobalTracks it contains.
*/
export function computeGlobalTracks(
profile: Profile,
tabID: TabID | null = null,
tabToThreadIndexesMap: Map<ThreadIndex, Set<TabID>>
): GlobalTrack[] {
// Defining this ProcessTrack type here helps flow understand the intent of
// the internals of this function, otherwise each GlobalTrack usage would need
// to check that it's a process type.
type ProcessTrack = {
type: 'process',
pid: Pid,
mainThreadIndex: number | null,
};
const globalTracksByPid: Map<Pid, ProcessTrack> = new Map();
let globalTracks: GlobalTrack[] = [];
// Create the global tracks.
for (
let threadIndex = 0;
threadIndex < profile.threads.length;
threadIndex++
) {
const thread = profile.threads[threadIndex];
const { pid, markers, stringTable } = thread;
if (thread.isMainThread) {
// This is a main thread, a global track needs to be created or updated with
// the main thread info.
let globalTrack = globalTracksByPid.get(pid);
if (globalTrack === undefined) {
// Create the track.
globalTrack = {
type: 'process',
pid,
mainThreadIndex: threadIndex,
};
globalTracks.push(globalTrack);
globalTracksByPid.set(pid, globalTrack);
} else {
// The main thread index was found, add it.
globalTrack.mainThreadIndex = threadIndex;
}
} else {
// This is a non-main thread.
if (!globalTracksByPid.has(pid)) {
// This is a thread without a known main thread. Create a global process
// track for it, but don't add a main thread for it.
const globalTrack = {
type: 'process',
pid: pid,
mainThreadIndex: null,
};
globalTracks.push(globalTrack);
globalTracksByPid.set(pid, globalTrack);
}
}
// Check for screenshots.
const ids: Set<string> = new Set();
if (stringTable.hasString('CompositorScreenshot')) {
const screenshotNameIndex = stringTable.indexForString(
'CompositorScreenshot'
);
for (let markerIndex = 0; markerIndex < markers.length; markerIndex++) {
if (markers.name[markerIndex] === screenshotNameIndex) {
// Coerce the payload to a screenshot one. Don't do a runtime check that
// this is correct.
const data: ScreenshotPayload = (markers.data[markerIndex]: any);
ids.add(data.windowID);
}
}
for (const id of ids) {
globalTracks.push({ type: 'screenshots', id, threadIndex });
}
}
}
// Add the visual progress tracks if we have visualMetrics data.
if (profile.meta && profile.meta.visualMetrics) {
const metrics = profile.meta.visualMetrics;
// Some metrics might be missing depending on the options specified to browsertime.
if (metrics.VisualProgress) {
globalTracks.push({ type: 'visual-progress' });
}
if (metrics.PerceptualSpeedIndexProgress) {
globalTracks.push({ type: 'perceptual-visual-progress' });
}
if (metrics.ContentfulSpeedIndexProgress) {
globalTracks.push({ type: 'contentful-visual-progress' });
}
}
// Filter the global tracks by current tab.
globalTracks = filterGlobalTracksByTab(
globalTracks,
profile,
tabID,
tabToThreadIndexesMap
);
// When adding a new track type, this sort ensures that the newer tracks are added
// at the end so that the global track indexes are stable and backwards compatible.
globalTracks.sort(
// In place sort!
(a, b) =>
GLOBAL_TRACK_INDEX_ORDER[a.type] - GLOBAL_TRACK_INDEX_ORDER[b.type]
);
return globalTracks;
}
/**
* Filter the global tracks by the current selected tab if it's specified.
*/
function filterGlobalTracksByTab(
globalTracks: GlobalTrack[],
profile: Profile,
tabID: TabID | null,
tabToThreadIndexesMap: Map<ThreadIndex, Set<TabID>>
): GlobalTrack[] {
if (tabID === null) {
// Return the global tracks if there is no tab filter.
return globalTracks;
}
const threadIndexes = tabToThreadIndexesMap.get(tabID);
if (!threadIndexes) {
// This is not really a possible path. It might indicate a bug on the frontend
// or backend.
console.warn(`Failed to find the thread indexes for given tab ${tabID}`);
return globalTracks;
}
// Filter the tracks by the tab filter.
const newGlobalTracks = [];
for (const globalTrack of globalTracks) {
switch (globalTrack.type) {
case 'process': {
const { mainThreadIndex } = globalTrack;
if (mainThreadIndex === null) {
// Do not include the global track if it doesn't have any main thread
// index.
continue;
}
const thread = profile.threads[mainThreadIndex];
if (
// Always add the parent process main thread.
(thread.isMainThread && thread.processType === 'default') ||
threadIndexes.has(mainThreadIndex)
) {
newGlobalTracks.push(globalTrack);
}
break;
}
// Always include the screenshots.
case 'screenshots':
// Also always add the visual progress tracks without looking at the tab
// filter. (fallthrough)
case 'visual-progress':
case 'perceptual-visual-progress':
case 'contentful-visual-progress':
newGlobalTracks.push(globalTrack);
break;
default:
throw new Error('Unhandled globalTack type.');
}
}
return newGlobalTracks;
}
/**
* Determine the display order for the global tracks, which will be different the
* initial ordering of the tracks, as the initial ordering must remain stable as
* new tracks are added.
*/
export function initializeGlobalTrackOrder(
// This is the list of the tracks.
globalTracks: GlobalTrack[],
// If viewing an existing profile, take the track ordering from the URL and sanitize it.
urlGlobalTrackOrder: TrackIndex[] | null,
// If viewing an old profile URL, there were not tracks, only thread indexes. Turn
// the legacy ordering into track ordering.
legacyThreadOrder: ThreadIndex[] | null
): TrackIndex[] {
if (legacyThreadOrder !== null) {
// Upgrade an older URL value based on the thread index to the track index based
// ordering. Don't trust that the thread indexes are actually valid.
const trackOrder = [];
// Convert the thread index to a track index, if it's valid.
for (const threadIndex of legacyThreadOrder) {
const trackIndex = globalTracks.findIndex(
(globalTrack) =>
globalTrack.type === 'process' &&
globalTrack.mainThreadIndex === threadIndex
);
if (trackIndex !== -1) {
trackOrder.push(trackIndex);
}
}
// Add the remaining track indexes.
for (let trackIndex = 0; trackIndex < globalTracks.length; trackIndex++) {
if (!trackOrder.includes(trackIndex)) {
trackOrder.push(trackIndex);
}
}
return trackOrder;
}
if (
urlGlobalTrackOrder !== null &&
urlGlobalTrackOrder.length !== globalTracks.length
) {
// The URL track order length doesn't match the tracks we've generated. Most likely
// this means that we have generated new tracks that the URL does not know about.
// Add on indexes at the end for the new tracks. These new indexes will still be
// checked by the _indexesAreValid function below.s
const newOrder = urlGlobalTrackOrder.slice();
for (let i = urlGlobalTrackOrder.length; i < globalTracks.length; i++) {
newOrder.push(i);
}
urlGlobalTrackOrder = newOrder;
}
return urlGlobalTrackOrder !== null &&
_indexesAreValid(globalTracks.length, urlGlobalTrackOrder)
? urlGlobalTrackOrder
: _getDefaultGlobalTrackOrder(globalTracks);
}
// Returns the selected thread (set), intersected with the set of visible threads.
// Falls back to the default thread selection.
export function initializeSelectedThreadIndex(
selectedThreadIndexes: Set<ThreadIndex> | null,
visibleThreadIndexes: ThreadIndex[],
profile: Profile
): Set<ThreadIndex> {
if (selectedThreadIndexes === null) {
return getDefaultSelectedThreadIndexes(visibleThreadIndexes, profile);
}
// Filter out hidden threads from the set of selected threads.
const visibleSelectedThreadIndexes = intersectSets(
selectedThreadIndexes,
new Set(visibleThreadIndexes)
);
if (visibleSelectedThreadIndexes.size === 0) {
// No selected threads were visible. Fall back to default selection.
return getDefaultSelectedThreadIndexes(visibleThreadIndexes, profile);
}
return visibleSelectedThreadIndexes;
}
// Select either the GeckoMain [tab] thread, or the first thread in the thread
// order.
function getDefaultSelectedThreadIndexes(
visibleThreadIndexes: ThreadIndex[],
profile: Profile
): Set<ThreadIndex> {
if (profile.meta.initialSelectedThreads !== undefined) {
return new Set(
profile.meta.initialSelectedThreads.filter((threadIndex) => {
if (threadIndex < profile.threads.length) {
return true;
}
console.warn(
`The specified thread index ${threadIndex} is higher than the maximum thread index ${
profile.threads.length - 1
}.`
);
return false;
})
);
}
const visibleThreads = visibleThreadIndexes.map(
(threadIndex) => profile.threads[threadIndex]
);
const defaultThread = _findDefaultThread(visibleThreads);
const defaultThreadIndex = profile.threads.indexOf(defaultThread);
if (defaultThreadIndex === -1) {
throw new Error('Expected to find a thread index to select.');
}
return new Set([defaultThreadIndex]);
}
// Returns either a configuration of hidden tracks that has at least one
// visible thread, or null.
export function tryInitializeHiddenTracksLegacy(
tracksWithOrder: TracksWithOrder,
legacyHiddenThreads: ThreadIndex[],
profile: Profile
): HiddenTracks | null {
const allThreads = new Set(profile.threads.map((_thread, i) => i));
const hiddenThreadsSet = new Set(legacyHiddenThreads);
const visibleThreads = subtractSets(allThreads, hiddenThreadsSet);
if (visibleThreads.size === 0) {
return null;
}
return _computeHiddenTracksForVisibleThreads(
profile,
visibleThreads,
tracksWithOrder
);
}
// Returns either a configuration of hidden tracks that has at least one
// visible thread, or null.
export function tryInitializeHiddenTracksFromUrl(
tracksWithOrder: TracksWithOrder,
urlHiddenGlobalTracks: Set<TrackIndex>,
urlHiddenLocalTracksByPid: Map<Pid, Set<TrackIndex>>
): HiddenTracks | null {
const hiddenGlobalTracks = intersectSets(
new Set(tracksWithOrder.globalTrackOrder),
urlHiddenGlobalTracks
);
const hiddenLocalTracksByPid = new Map();
for (const [pid, localTrackOrder] of tracksWithOrder.localTrackOrderByPid) {
const localTracks = new Set(localTrackOrder);
const hiddenLocalTracks = intersectSets(
localTracks,
urlHiddenLocalTracksByPid.get(pid) || new Set()
);
hiddenLocalTracksByPid.set(pid, hiddenLocalTracks);
if (hiddenLocalTracks.size === localTracks.size) {
// All local tracks of this process were hidden.
// If the main thread was not recorded for this process, hide the (empty) process track as well.
const globalTrackIndex = tracksWithOrder.globalTracks.findIndex(
(globalTrack) =>
globalTrack.type === 'process' &&
globalTrack.pid === pid &&
globalTrack.mainThreadIndex === null
);
if (globalTrackIndex !== -1) {
// An empty global track was found, hide it.
hiddenGlobalTracks.add(globalTrackIndex);
}
}
}
const hiddenTracks = { hiddenGlobalTracks, hiddenLocalTracksByPid };
if (getVisibleThreads(tracksWithOrder, hiddenTracks).length === 0) {
return null;
}
return hiddenTracks;
}
// Returns the default configuration of hidden global and local tracks.
// The result is guaranteed to have a non-empty number of visible threads.
export function computeDefaultHiddenTracks(
tracksWithOrder: TracksWithOrder,
profile: Profile,
threadActivityScores: Array<ThreadActivityScore>,
includeParentProcessThreads: boolean
): HiddenTracks {
return _computeHiddenTracksForVisibleThreads(
profile,
computeDefaultVisibleThreads(
profile,
tracksWithOrder,
threadActivityScores,
includeParentProcessThreads
),
tracksWithOrder
);
}
// Create the sets of global and local tracks so that the requested
// threads are visible. Non-process global tracks and non-thread local
// tracks are always visible.
// Some main threads can be visible even if they were not requested to
// be visible. This happens if their global track contains visible local
// tracks.
function _computeHiddenTracksForVisibleThreads(
profile: Profile,
visibleThreadIndexes: Set<ThreadIndex>,
tracksWithOrder: TracksWithOrder
): HiddenTracks {
const visiblePids = new Set(
[...visibleThreadIndexes].map((i) => profile.threads[i].pid)
);
const hiddenGlobalTracks = new Set(
tracksWithOrder.globalTrackOrder.filter((trackIndex) => {
const globalTrack = tracksWithOrder.globalTracks[trackIndex];
if (globalTrack.type !== 'process') {
// Keep non-process global tracks visible.
return false;
}
return !visiblePids.has(globalTrack.pid);
})
);
const hiddenLocalTracksByPid = new Map();
for (const [pid, localTrackOrder] of tracksWithOrder.localTrackOrderByPid) {
if (!visiblePids.has(pid)) {
// Hide all local tracks.
hiddenLocalTracksByPid.set(pid, new Set(localTrackOrder));
continue;
}
const localTracks = tracksWithOrder.localTracksByPid.get(pid) ?? [];
const hiddenLocalTracks = new Set(
localTrackOrder.filter((localTrackIndex) => {
const localTrack = localTracks[localTrackIndex];
return !_isLocalTrackVisible(localTrack, visibleThreadIndexes);
})
);
hiddenLocalTracksByPid.set(pid, hiddenLocalTracks);
}
return { hiddenGlobalTracks, hiddenLocalTracksByPid };
}
// Return the list of threads which are visible in the supplied hidden
// tracks configuration.
export function getVisibleThreads(
{ globalTracks, localTracksByPid }: TracksWithOrder,
{ hiddenGlobalTracks, hiddenLocalTracksByPid }: HiddenTracks
): ThreadIndex[] {
const visibleThreads = [];
for (
let globalTrackIndex = 0;
globalTrackIndex < globalTracks.length;
globalTrackIndex++
) {
if (hiddenGlobalTracks.has(globalTrackIndex)) {
continue;
}
const globalTrack = globalTracks[globalTrackIndex];
if (globalTrack.type === 'process') {
const { mainThreadIndex, pid } = globalTrack;
if (mainThreadIndex !== null) {
visibleThreads.push(mainThreadIndex);
}
const tracks = ensureExists(
localTracksByPid.get(pid),
'A local track was expected to exist for the given pid.'
);
const hiddenTracks = ensureExists(
hiddenLocalTracksByPid.get(pid),
'Hidden tracks were expected to exists for the given pid.'
);
for (
let localTrackIndex = 0;
localTrackIndex < tracks.length;
localTrackIndex++
) {
const track = tracks[localTrackIndex];
if (track.type === 'thread') {
const { threadIndex } = track;
if (!hiddenTracks.has(localTrackIndex)) {
visibleThreads.push(threadIndex);
}
}
}
}
}
return visibleThreads;
}
export function getGlobalTrackName(
globalTrack: GlobalTrack,
threads: Thread[]
): string {
switch (globalTrack.type) {
case 'process': {
// Look up the thread information for the process if it exists.
if (globalTrack.mainThreadIndex === null) {
// No main thread was found for process track, so it is empty. This can
// happen for instance when recording "DOM Worker" but not "GeckoMain". The
// "DOM Worker" thread will be captured, but not the main thread, thus leaving
// a process track with no main thread.
// It can also happen when importing other profile formats.
// First, see if any thread in this process has a non-empty processName.
const pid = globalTrack.pid;
const processName = threads
.filter((thread) => thread.pid === pid)
.map((thread) => thread.processName)
.find((processName) => !!processName);
if (processName) {
return processName;
}
// Fallback: Use the PID.
return `Process ${pid}`;
}
// Getting the friendly thread name and removing the scheme in case we
// have any eTLD+1 returned. This can happen if the thread is an Isolated
// Web Content process' main thread that has an `eTLD+1` field. Removing the
// scheme to fit the complete url in this limited space in the timeline.
return getFriendlyThreadName(
threads,
threads[globalTrack.mainThreadIndex]
).replace(/^https?:\/\//i, '');
}
case 'screenshots':
return 'Screenshots';
case 'visual-progress':
return 'Visual Progress';
case 'perceptual-visual-progress':
return 'Perceptual Visual Progress';
case 'contentful-visual-progress':
return 'Contentful Visual Progress';
default:
throw assertExhaustiveCheck(globalTrack, 'Unhandled GlobalTrack type.');
}
}
export function getLocalTrackName(
localTrack: LocalTrack,
threads: Thread[],
counters: Counter[]
): string {
switch (localTrack.type) {
case 'thread':
return getFriendlyThreadName(threads, threads[localTrack.threadIndex]);
case 'network':
return 'Network';
case 'memory':
return 'Memory';
case 'bandwidth':
return 'Bandwidth';
case 'ipc':
return `IPC — ${getFriendlyThreadName(
threads,
threads[localTrack.threadIndex]
)}`;
case 'event-delay':
return (