forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
receive-profile.test.js
2314 lines (2025 loc) · 79 KB
/
receive-profile.test.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 { oneLineTrim } from 'common-tags';
import JSZip from 'jszip';
import { indexedDB } from 'fake-indexeddb';
import { ensureExists } from 'firefox-profiler/utils/flow';
import {
getEmptyProfile,
getEmptyThread,
} from '../../profile-logic/data-structures';
import { getTimeRangeForThread } from '../../profile-logic/profile-data';
import { viewProfileFromPathInZipFile } from '../../actions/zipped-profiles';
import * as ProfileViewSelectors from '../../selectors/profile';
import * as ZippedProfilesSelectors from '../../selectors/zipped-profiles';
import * as UrlStateSelectors from '../../selectors/url-state';
import {
getThreadSelectors,
selectedThreadSelectors,
} from '../../selectors/per-thread';
import { getView } from '../../selectors/app';
import { urlFromState } from '../../app-logic/url-handling';
import { createBrowserConnection } from '../../app-logic/browser-connection';
import {
viewProfile,
finalizeProfileView,
retrieveProfileFromBrowser,
retrieveProfileFromStore,
retrieveProfileOrZipFromUrl,
retrieveProfileFromFile,
retrieveProfilesToCompare,
_fetchProfile,
retrieveProfileForRawUrl,
changeTimelineTrackOrganization,
} from '../../actions/receive-profile';
import { SymbolsNotFoundError } from '../../profile-logic/errors';
import { createGeckoProfile } from '../fixtures/profiles/gecko-profile';
import { blankStore, storeWithProfile } from '../fixtures/stores';
import {
makeProfileSerializable,
processGeckoProfile,
serializeProfile,
} from '../../profile-logic/process-profile';
import {
getProfileFromTextSamples,
getMergedProfileFromTextSamples,
addMarkersToThreadWithCorrespondingSamples,
getProfileWithMarkers,
getProfileWithThreadCPUDelta,
} from '../fixtures/profiles/processed-profile';
import {
getHumanReadableTracks,
getProfileWithNiceTracks,
} from '../fixtures/profiles/tracks';
import { waitUntilState } from '../fixtures/utils';
import { dataUrlToBytes } from 'firefox-profiler/utils/base64';
import { compress } from '../../utils/gz';
import type { Profile, FaviconData } from 'firefox-profiler/types';
// Mocking SymbolStoreDB. By default the functions will return undefined, which
// will make the symbolication move forward with some bogus information.
// If you need to simulate that it doesn't have the information, use the
// function simulateSymbolStoreHasNoCache defined below.
import SymbolStoreDB from '../../profile-logic/symbol-store-db';
jest.mock('../../profile-logic/symbol-store-db');
// Mocking expandUrl
// We mock this module because it's tested more properly in its unit
// tests and it isn't necessary to run through it in this test file. Moreover
// it makes it easier to mock `fetch` calls that fetch a profile from a store.
import { expandUrl } from '../../utils/shorten-url';
jest.mock('../../utils/shorten-url');
import {
simulateOldWebChannelAndFrameScript,
simulateWebChannel,
} from '../fixtures/mocks/web-channel';
function simulateSymbolStoreHasNoCache() {
// SymbolStoreDB is a mock, but Flow doesn't know this. That's why we use
// `any` so that we can use `mockImplementation`.
(SymbolStoreDB: any).mockImplementation(() => ({
getSymbolTable: jest
.fn()
.mockImplementation((debugName, breakpadId) =>
Promise.reject(
new SymbolsNotFoundError(
'The requested library does not exist in the database.',
{ debugName, breakpadId }
)
)
),
}));
}
describe('actions/receive-profile', function () {
beforeEach(() => {
// The SymbolStore requires the use of IndexedDB, ensure that it exists so that
// symbolication can happen.
window.indexedDB = indexedDB;
});
afterEach(() => {
delete window.indexedDB;
});
/**
* This function allows to observe all state changes in a Redux store while
* something's going on.
* @param {ReduxStore} store
* @param {() => Promise<any>} func Process that will be started while
* observing the store.
* @returns {Promise<State[]>} All states that happened while waiting for
* the end of func.
*/
async function observeStoreStateChanges(store, func) {
const states = [];
const unsubscribe = store.subscribe(() => {
states.push(store.getState());
});
await func();
unsubscribe();
return states;
}
function encode(string) {
return new TextEncoder().encode(string);
}
describe('viewProfile', function () {
it('can take a profile and view it', function () {
const store = blankStore();
expect(() => {
ProfileViewSelectors.getProfile(store.getState());
}).toThrow();
const initialProfile = ProfileViewSelectors.getProfileOrNull(
store.getState()
);
expect(initialProfile).toBeNull();
const profile = _getSimpleProfile();
store.dispatch(viewProfile(profile));
expect(ProfileViewSelectors.getProfile(store.getState())).toBe(profile);
});
it('will be a fatal error if a profile has no threads', function () {
const store = blankStore();
expect(getView(store.getState()).phase).toBe('INITIALIZING');
const emptyProfile = getEmptyProfile();
// Stop console.error from spitting out an error message:
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
store.dispatch(viewProfile(emptyProfile));
expect(getView(store.getState()).phase).toBe('FATAL_ERROR');
expect(spy).toHaveBeenCalled();
});
function getProfileWithIdleAndWorkThread() {
const { profile } = getProfileFromTextSamples(
`A[cat:Idle] A[cat:Idle] A[cat:Idle] A[cat:Idle] A[cat:Idle]`,
`work work work work work work work`
);
const [idleThread, workThread] = profile.threads;
const idleCategoryIndex = ensureExists(
profile.meta.categories,
'Expected to find categories'
).findIndex((c) => c.name === 'Idle');
expect(idleCategoryIndex).not.toBe(-1);
workThread.name = 'Work Thread';
idleThread.name = 'Idle Thread';
idleThread.stackTable.category = idleThread.stackTable.category.map(
() => idleCategoryIndex
);
return { profile, idleThread, workThread };
}
it('will hide threads with idle samples', function () {
const store = blankStore();
const { profile } = getProfileWithIdleAndWorkThread();
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - hide [thread Idle Thread]',
' - show [thread Work Thread] SELECTED',
]);
});
it('will not hide the Windows GPU thread', function () {
const store = blankStore();
const { profile, idleThread, workThread } =
getProfileWithIdleAndWorkThread();
idleThread.name = 'GeckoMain';
idleThread.isMainThread = true;
idleThread.pid = '0';
workThread.name = 'GeckoMain';
workThread.isMainThread = true;
idleThread.pid = '1';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [thread GeckoMain default] SELECTED',
'show [thread GeckoMain default]',
]);
});
it('will not hide a main thread', function () {
const store = blankStore();
const { profile, idleThread, workThread } =
getProfileWithIdleAndWorkThread();
idleThread.name = 'GeckoMain';
idleThread.isMainThread = true;
idleThread.pid = '0';
workThread.name = 'GeckoMain';
workThread.isMainThread = true;
workThread.pid = '1';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [thread GeckoMain default] SELECTED',
'show [thread GeckoMain default]',
]);
});
it('will not hide the only global track', function () {
const store = blankStore();
const { profile } = getProfileFromTextSamples(
`A[cat:Idle] A[cat:Idle] A[cat:Idle] A[cat:Idle] A[cat:Idle]`,
`work work work work work`
);
const [threadA, threadB] = profile.threads;
threadA.name = 'GeckoMain';
threadA.isMainThread = true;
threadA.processType = 'tab';
threadA.pid = '111';
threadB.name = 'Other';
threadB.pid = '111';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [thread GeckoMain tab] SELECTED',
' - show [thread Other]',
]);
});
it('will hide idle content threads', function () {
const store = blankStore();
const { profile } = getProfileFromTextSamples(
`A[cat:Idle] A[cat:Idle] A[cat:Idle] A[cat:Idle] A[cat:Idle]`,
`work work work work work work work`,
`C[cat:Idle] C[cat:Idle] C[cat:Idle] C[cat:Idle] C[cat:Idle]`
);
profile.threads.forEach((thread, threadIndex) => {
thread.name = 'GeckoMain';
thread.isMainThread = true;
thread.processType = 'tab';
thread.pid = `${threadIndex}`;
});
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'hide [thread GeckoMain tab]',
'show [thread GeckoMain tab] SELECTED',
'hide [thread GeckoMain tab]',
]);
});
it('will not hide non-idle content threads', function () {
const store = blankStore();
const { profile } = getProfileFromTextSamples(
`work work work work work work work`,
`work work work work work work work`,
`C[cat:Idle] C[cat:Idle] C[cat:Idle] work work`
);
profile.threads.forEach((thread, threadIndex) => {
thread.name = 'GeckoMain';
thread.isMainThread = true;
thread.processType = 'tab';
thread.pid = `${threadIndex}`;
});
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [thread GeckoMain tab] SELECTED',
'show [thread GeckoMain tab]',
'show [thread GeckoMain tab]',
]);
});
it('will hide an empty global track when all child tracks are hidden', function () {
const store = blankStore();
const { profile } = getProfileFromTextSamples(
`work work work work work`, // pid 1
`work work work work work`, // pid 1
`idle[cat:Idle] idle[cat:Idle] idle[cat:Idle] idle[cat:Idle] idle[cat:Idle]`, // pid 2
`work work work work work` // pid 3
);
profile.threads[0].name = 'Work A';
profile.threads[1].name = 'Work B';
profile.threads[2].name = 'Idle C';
profile.threads[3].name = 'Work E';
profile.threads[0].pid = '1';
profile.threads[1].pid = '1';
profile.threads[2].pid = '2';
profile.threads[3].pid = '3';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - show [thread Work A] SELECTED',
' - show [thread Work B]',
'hide [process]', // <- Ensure this process is hidden.
' - hide [thread Idle C]',
'show [process]',
' - show [thread Work E]',
]);
});
it('will not hide audio tracks if they have at least one sample', function () {
const store = blankStore();
const idleThread: Array<string> = (Array.from({
length: 100,
}): any).fill('idle[cat:Idle]');
const idleThreadString = idleThread.join(' ');
// We want 1 work sample in 100 samples for each thread.
const oneWorkSampleThread = idleThread.slice();
oneWorkSampleThread[1] = 'work';
const oneWorkSampleThreadString = oneWorkSampleThread.join(' ');
const { profile } = getProfileFromTextSamples(
oneWorkSampleThreadString, // AudioIPC
oneWorkSampleThreadString, // MediaPDecoder
oneWorkSampleThreadString, // MediaTimer
oneWorkSampleThreadString, // MediaPlayback
oneWorkSampleThreadString, // MediaDecoderStateMachine
idleThreadString, // AudioIPC
idleThreadString, // MediaPDecoder
idleThreadString, // MediaTimer
idleThreadString, // MediaPlayback
idleThreadString // MediaDecoderStateMachine
);
profile.threads[0].name = 'AudioIPC work';
profile.threads[1].name = 'MediaPDecoder work';
profile.threads[2].name = 'MediaTimer work';
profile.threads[3].name = 'MediaPlayback work';
profile.threads[4].name = 'MediaDecoderStateMachine work';
profile.threads[5].name = 'AudioIPC idle';
profile.threads[6].name = 'MediaPDecoder idle';
profile.threads[7].name = 'MediaTimer idle';
profile.threads[8].name = 'MediaPlayback idle';
profile.threads[9].name = 'MediaDecoderStateMachine idle';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - hide [thread AudioIPC idle]', // hidden
' - show [thread AudioIPC work] SELECTED',
' - hide [thread MediaDecoderStateMachine idle]', // hidden
' - show [thread MediaDecoderStateMachine work]',
' - hide [thread MediaPDecoder idle]', // hidden
' - show [thread MediaPDecoder work]',
' - hide [thread MediaPlayback idle]', // hidden
' - show [thread MediaPlayback work]',
' - hide [thread MediaTimer idle]', // hidden
' - show [thread MediaTimer work]',
]);
});
it('will hide non-idle but short-lived threads', function () {
const store = blankStore();
const { profile } = getProfileFromTextSamples(
// 2 samples of work
`work work`,
// 41 samples of work (2 / 41 < 0.05)
Array(41).fill('work').join(' ')
);
profile.threads.forEach((thread, threadIndex) => {
thread.name = 'GeckoMain';
thread.isMainThread = true;
thread.processType = 'tab';
thread.pid = `${threadIndex}`;
});
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'hide [thread GeckoMain tab]',
'show [thread GeckoMain tab] SELECTED',
]);
});
it(`won't hide any tracks in a profile resulting from a compare operation`, () => {
const { profile } = getMergedProfileFromTextSamples([
'A',
'A '.repeat(100),
]);
const store = storeWithProfile(profile);
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [thread Empty default] SELECTED',
'show [thread Empty default]',
'show [thread Diff between 1 and 2 comparison]',
]);
});
describe('with threadCPUDelta', function () {
it('will show a thread when the relative CPU usage is above 10%', function () {
const store = blankStore();
// A profile with an accumulated value of 430 in the first thread. Therefore the
// 10% threshold for a non-idle thread's accumulated CPU usage is 43.
const profile = getProfileWithThreadCPUDelta([
[15, 20, 100, 50, 80, 40, 60, 20, 20, 25], // Thread with 430 sample score
[5, 6, 1, 11, 0, 7, 0, 12, 14, 0], // Thread with 56 sample score
]);
profile.threads[0].name = 'Thread with 100% CPU';
profile.threads[1].name = 'Thread with 13% CPU';
profile.threads[0].pid = '1';
profile.threads[1].pid = '1';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - show [thread Thread with 13% CPU]', // <- Ensure this thread is not hidden.
' - show [thread Thread with 100% CPU] SELECTED',
]);
});
it('will hide a thread when the relative CPU percentage is below 5%', function () {
const store = blankStore();
// A profile with an accumulated value of 519 in the first thread. Therefore the
// 5% threshold for a non-idle thread's accumulated CPU usage is 25.95.
const profile = getProfileWithThreadCPUDelta([
[15, 20, 100, 50, 80, 40, 60, 72, 57, 25], // Thread with 519 sample score
[5, 3, 1, 4, 1, 4, 0, 2, 4, 1], // Thread with 25 sample score
]);
profile.threads[0].name = 'Thread with 100% CPU';
profile.threads[1].name = 'Thread with 4% CPU';
profile.threads[0].pid = '1';
profile.threads[1].pid = '1';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - hide [thread Thread with 4% CPU]', // <- Ensure this thread is hidden.
' - show [thread Thread with 100% CPU] SELECTED',
]);
});
it('will hide a thread when the relative CPU percentage is below 5% even if it has more samples with > 90% CPU delta', function () {
const store = blankStore();
const profile = getProfileWithThreadCPUDelta([
[1, 2, 92, 93, 94, 1, 1, 1, 1], // Thread with 286 sample score (< 315 == 6300 * 0.05)
new Array(700).fill(9), // Thread with 700 * 9 = 6300 sample score
]);
profile.threads[0].name = 'Thread with a very short burst of > 90% CPU';
profile.threads[1].name = 'Thread with sustained 9% CPU';
profile.threads[0].pid = '1';
profile.threads[1].pid = '1';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - hide [thread Thread with a very short burst of > 90% CPU]', // <- Ensure this thread is hidden.
' - show [thread Thread with sustained 9% CPU] SELECTED',
]);
});
it('will show the only thread regardless of CPU activity', function () {
const store = blankStore();
const profile = getProfileWithThreadCPUDelta([
// Thread with 1 sample with high CPU delta and all other samples < 10% CPU delta.
[1, 2, 100, 4, 1, 2, 6, 8, 6, 9],
]);
profile.threads[0].name = 'Thread with 10% CPU';
profile.threads[0].pid = '1';
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - show [thread Thread with 10% CPU] SELECTED', // <- Ensure this thread is not hidden.
]);
});
it(`won't hide any tracks in a profile resulting from a compare operation`, () => {
const { profile } = getMergedProfileFromTextSamples(
['A A A A', 'B B B B'],
[
{
threadCPUDelta: [10, 10, 10, 10_000_000],
threadCPUDeltaUnit: 'ns',
},
{
threadCPUDelta: [10, 10_000_000, 10, 25],
threadCPUDeltaUnit: 'ns',
},
]
);
const store = storeWithProfile(profile);
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [thread Empty default] SELECTED',
'show [thread Empty default]',
'show [thread Diff between 1 and 2 comparison]',
]);
});
});
describe('too many threads', function () {
it('will limit the visible threads to 15', function () {
const store = blankStore();
// A profile with 18 threads, with varying thread scores.
// The three threads with the lowest thread CPU delta sum should be hidden.
const profile = getProfileWithThreadCPUDelta([
[100, 10, 20, 30, 20, 10, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 70, 40, 50, 0, 0, 0, 0],
[0, 0, 80, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0],
[0, 0, 0, 60, 0, 70, 60, 80, 0, 0, 0, 0, 0],
[0, 0, 40, 0, 0, 50, 0, 0, 0, 80, 80, 80, 0],
[30, 30, 0, 0, 0, 0, 40, 0, 0, 0, 80, 0, 0],
[0, 0, 0, 0, 90, 50, 0, 0, 0, 90, 80, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 30, 40, 0, 0, 90, 60, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 80, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 60, 60, 80, 70, 80, 0, 0],
[0, 0, 0, 0, 20, 30, 0, 0, 0, 80, 0, 0, 0],
[0, 0, 0, 70, 0, 0, 0, 0, 10, 10, 10, 0, 10],
[0, 0, 0, 80, 0, 0, 50, 40, 60, 0, 0, 0, 0],
[10, 20, 80, 30, 90, 90, 60, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 60, 80, 0, 0, 0],
[0, 20, 0, 0, 0, 100, 100, 100, 0, 0, 0, 0, 0],
]);
for (let i = 0; i < profile.threads.length; i++) {
const thread = profile.threads[i];
const cpuDeltaSum = ensureExists(
thread.samples.threadCPUDelta
).reduce((accum, delta) => accum + (delta ?? 0), 0);
thread.processName = 'Single Process';
thread.pid = '0';
thread.name = `Thread with ${cpuDeltaSum} CPU`;
thread.tid = i;
}
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - hide [thread Thread with 0 CPU]', // <-- hidden
' - hide [thread Thread with 30 CPU]', // <-- hidden
' - hide [thread Thread with 100 CPU]', // <-- hidden
' - show [thread Thread with 110 CPU]',
' - show [thread Thread with 120 CPU]',
' - show [thread Thread with 130 CPU]',
' - show [thread Thread with 140 CPU]',
' - show [thread Thread with 160 CPU]',
' - show [thread Thread with 180 CPU]',
' - show [thread Thread with 190 CPU] SELECTED',
' - show [thread Thread with 220 CPU]',
' - show [thread Thread with 230 CPU]',
' - show [thread Thread with 270 CPU]',
' - show [thread Thread with 310 CPU]',
' - show [thread Thread with 320 CPU]',
' - show [thread Thread with 330 CPU]',
' - show [thread Thread with 350 CPU]',
' - show [thread Thread with 380 CPU]',
]);
});
it('will keep certain threads visible even if they have low CPU usage', function () {
const store = blankStore();
// A profile with 18 threads, with varying thread scores.
const profile = getProfileWithThreadCPUDelta([
[100, 10, 20, 30, 20, 10, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 10, 10, 0, 0, 0, 0, 0],
[0, 0, 80, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0],
[0, 0, 0, 60, 0, 70, 60, 80, 0, 0, 0, 0, 0],
[0, 0, 40, 0, 0, 50, 0, 0, 0, 80, 80, 80, 0],
[30, 30, 0, 0, 0, 0, 40, 0, 0, 0, 80, 0, 0],
[0, 0, 0, 0, 90, 50, 0, 0, 0, 90, 80, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 30, 40, 0, 0, 90, 60, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 80, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 60, 60, 80, 70, 80, 0, 0],
[0, 0, 0, 0, 20, 30, 0, 0, 0, 80, 0, 0, 0],
[0, 0, 0, 70, 0, 0, 0, 0, 10, 10, 10, 0, 10],
[0, 0, 0, 80, 0, 0, 50, 40, 60, 0, 0, 0, 0],
[10, 20, 80, 30, 90, 90, 60, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 60, 80, 0, 0, 0],
[0, 20, 0, 0, 0, 100, 100, 100, 0, 0, 0, 0, 0],
]);
for (let i = 0; i < profile.threads.length; i++) {
const thread = profile.threads[i];
const cpuDeltaSum = ensureExists(
thread.samples.threadCPUDelta
).reduce((accum, delta) => accum + (delta ?? 0), 0);
thread.processName = 'Single Process';
thread.pid = '0';
thread.name = `Thread with ${cpuDeltaSum} CPU`;
thread.tid = i;
}
profile.threads[1].name = 'Renderer'; // with 20 CPU
profile.threads[2].name = 'DOM Worker'; // with 100 CPU
store.dispatch(viewProfile(profile));
expect(getHumanReadableTracks(store.getState())).toEqual([
'show [process]',
' - show [thread DOM Worker]',
' - hide [thread Renderer]', // <-- hidden
' - hide [thread Thread with 0 CPU]', // <-- hidden
' - hide [thread Thread with 30 CPU]', // <-- hidden
' - show [thread Thread with 110 CPU]',
' - show [thread Thread with 120 CPU]',
' - show [thread Thread with 130 CPU]',
' - show [thread Thread with 140 CPU]',
' - show [thread Thread with 180 CPU]',
' - show [thread Thread with 190 CPU] SELECTED',
' - show [thread Thread with 220 CPU]',
' - show [thread Thread with 230 CPU]',
' - show [thread Thread with 270 CPU]',
' - show [thread Thread with 310 CPU]',
' - show [thread Thread with 320 CPU]',
' - show [thread Thread with 330 CPU]',
' - show [thread Thread with 350 CPU]',
' - show [thread Thread with 380 CPU]',
]);
});
});
// Ideas for further tests:
// - A test which checks which threads get hidden when there a both threads
// with CPU deltas and threads without CPU deltas.
// - The above, but with an interval of 5ms instead of 1ms, such that it
// would have caught a bug where I divided by the interval instead of
// multiplying by it.
// - A test with active audio threads and active non-audio threads, making
// sure that the active non-audio threads aren't hidden. (Hiding active
// non-audio threads could happen if the hiding was based on the
// boostedSampleScore rather than the sampleScore.)
});
describe('changeTimelineTrackOrganization', function () {
const tabID = 123;
const innerWindowID = 111111;
function setup({
profile,
initializeCtxId = false,
}: {
profile?: Profile,
initializeCtxId?: boolean,
}) {
const store = blankStore();
if (!profile) {
profile = getEmptyProfile();
profile.threads.push(
getEmptyThread({ name: 'GeckoMain', processType: 'tab', pid: '1' })
);
}
profile.meta.configuration = {
threads: [],
features: [],
capacity: 1000000,
activeTabID: tabID,
};
profile.pages = [
{
tabID: tabID,
innerWindowID: innerWindowID,
url: 'URL',
embedderInnerWindowID: 0,
},
];
store.dispatch(viewProfile(profile));
if (initializeCtxId) {
store.dispatch(
changeTimelineTrackOrganization({
type: 'active-tab',
tabID,
})
);
}
return { ...store, profile };
}
it('should be able to switch to active tab view from the full view', function () {
const { dispatch, getState } = setup({ initializeCtxId: false });
expect(
UrlStateSelectors.getTimelineTrackOrganization(getState())
).toEqual({
type: 'full',
});
dispatch(
changeTimelineTrackOrganization({
type: 'active-tab',
tabID,
})
);
expect(
UrlStateSelectors.getTimelineTrackOrganization(getState())
).toEqual({
type: 'active-tab',
tabID,
});
});
it('should be able to switch to full view from the active tab', function () {
const { dispatch, getState } = setup({ initializeCtxId: true });
expect(
UrlStateSelectors.getTimelineTrackOrganization(getState())
).toEqual({
type: 'active-tab',
tabID,
});
dispatch(changeTimelineTrackOrganization({ type: 'full' }));
expect(
UrlStateSelectors.getTimelineTrackOrganization(getState())
).toEqual({
type: 'full',
});
});
it('should reset the url state while switching to the full view', function () {
// Get a profile with nice tracks, so we can test that it's not automatically
// select the first thread.
const profile = getProfileWithNiceTracks();
const { dispatch, getState } = setup({ profile, initializeCtxId: true });
// Make sure that we start with the active-tab view.
expect(
UrlStateSelectors.getTimelineTrackOrganization(getState())
).toEqual({
type: 'active-tab',
tabID,
});
// Now switch to the full view and test that it will select the second track.
dispatch(changeTimelineTrackOrganization({ type: 'full' }));
expect(
UrlStateSelectors.getTimelineTrackOrganization(getState())
).toEqual({
type: 'full',
});
// It should find the best non-idle thread instead of selecting the first
// one automatically.
expect(
UrlStateSelectors.getSelectedThreadIndexes(getState())
).toMatchObject(new Set([1]));
});
});
describe('retrieveProfileFromBrowser', function () {
function toUint8Array(json) {
return encode(JSON.stringify(json));
}
function _setup(profileAs = 'json') {
jest.useFakeTimers();
const profileJSON = createGeckoProfile();
const profileGetter = async () => {
switch (profileAs) {
case 'json':
return profileJSON;
case 'arraybuffer':
return toUint8Array(profileJSON).buffer;
case 'gzip':
return (await compress(toUint8Array(profileJSON))).buffer;
default:
throw new Error('unknown profiler format');
}
};
window.fetch.any({ throws: new Error('No symbolication API in place') });
simulateSymbolStoreHasNoCache();
// Silence the warnings coming from the failed symbolication attempts, and
// make sure that the logged error contains our error messages.
jest.spyOn(console, 'warn').mockImplementation((error) => {
expect(error).toBeInstanceOf(SymbolsNotFoundError);
expect(error.errors).toEqual(
expect.arrayContaining([
expect.objectContaining({
message:
'There was a problem with the symbolication API request to the symbol server: No symbolication API in place',
}),
expect.objectContaining({ message: 'No symbol tables available' }),
])
);
});
const store = blankStore();
return {
profileGetter,
store,
};
}
function setupWithFrameScript(profileAs: string = 'json') {
const { store, profileGetter } = _setup(profileAs);
const geckoProfiler = {
getProfile: jest.fn().mockImplementation(() => profileGetter()),
getSymbolTable: jest
.fn()
.mockRejectedValue(new Error('No symbol tables available')),
};
const webChannel = simulateOldWebChannelAndFrameScript(geckoProfiler);
return {
geckoProfiler,
store,
...store,
...webChannel,
};
}
function setupWithWebChannel(
profileAs: string = 'json',
faviconsGetter?: () => Promise<Array<FaviconData | null>>
) {
const { store, profileGetter } = _setup(profileAs);
const webChannel = simulateWebChannel(profileGetter, faviconsGetter);
const waitUntilFavicons = () =>
waitUntilState(store, (state) => {
const pages = ProfileViewSelectors.getPageList(state);
if (!pages) {
return false;
}
return pages.some((page) => page.favicon);
});
return {
store,
...store,
...webChannel,
waitUntilFavicons,
};
}
afterEach(function () {
delete window.geckoProfilerPromise;
});
for (const setupWith of ['frame-script', 'web-channel']) {
for (const profileAs of ['json', 'arraybuffer', 'gzip']) {
it(`can retrieve a profile from the browser as ${profileAs} using ${setupWith}`, async function () {
const setupFn = {
'frame-script': setupWithFrameScript,
'web-channel': setupWithWebChannel,
}[setupWith];
const { dispatch, getState } = setupFn(profileAs);
const browserConnectionStatus =
await createBrowserConnection('Firefox/123.0');
await dispatch(retrieveProfileFromBrowser(browserConnectionStatus));
expect(console.warn).toHaveBeenCalledTimes(2);
const state = getState();
expect(getView(state)).toEqual({ phase: 'DATA_LOADED' });
expect(ProfileViewSelectors.getCommittedRange(state)).toEqual({
start: 0,
// The end can be computed as the sum of:
// - difference of the starts of the subprocess and the main process (1000)
// - the max of the last sample. (in this case, last sample's time is 6.
// - the interval (1)
end: 1007,
});
// not empty
expect(ProfileViewSelectors.getProfile(state).threads).toHaveLength(
3
);
});
}
}
it('tries to symbolicate the received profile, frame script version', async () => {
const { dispatch, geckoProfiler } = setupWithFrameScript();
const browserConnectionStatus =
await createBrowserConnection('Firefox/123.0');
await dispatch(retrieveProfileFromBrowser(browserConnectionStatus));
expect(geckoProfiler.getSymbolTable).toHaveBeenCalledWith(
'firefox',
expect.any(String)
);
expect(window.fetch).toHaveBeenCalledWith(
'https://symbolication.services.mozilla.com/symbolicate/v5',
expect.objectContaining({
body: expect.stringMatching(/memoryMap.*firefox/),
})
);
});
it('tries to symbolicate the received profile, webchannel version', async () => {
const { dispatch } = setupWithWebChannel();
const browserConnectionStatus =
await createBrowserConnection('Firefox/123.0');
await dispatch(retrieveProfileFromBrowser(browserConnectionStatus));
expect(window.fetch).toHaveBeenCalledWith(
'https://symbolication.services.mozilla.com/symbolicate/v5',
expect.objectContaining({
body: expect.stringMatching(/memoryMap.*firefox/),
})
);
});
it('gets the favicons for the received profile using webchannel', async () => {
// For some reason fetch-mock-jest removes the `data:` protocol.
const mockDataUrl = 'image/png,test';
window.fetch.get('image/png,test', {
arrayBuffer: () => {
return new Uint8Array([1, 2, 3, 4, 5, 6]).buffer;
},
});
// Create a simple urls getter for the pages.
const faviconsGetter = async (): Promise<Array<FaviconData | null>> => {
return [
{
data: await dataUrlToBytes('data:' + mockDataUrl),
mimeType: 'image/png',
},
null,
null,
];
};
const { dispatch, waitUntilFavicons } = setupWithWebChannel(
'json',
faviconsGetter
);
const browserConnectionStatus =
await createBrowserConnection('Firefox/134.0');
await dispatch(retrieveProfileFromBrowser(browserConnectionStatus));
// It should successfully get the favicons the profiles that are loaded from the browser.
return expect(waitUntilFavicons()).resolves.toBe(undefined);
});
});
describe('retrieveProfileFromStore', function () {
beforeEach(function () {
window.fetch.catch(403);
// Call the argument of setTimeout asynchronously right away
// (instead of waiting for the timeout).
jest
.spyOn(window, 'setTimeout')
.mockImplementation((callback) => process.nextTick(callback));
});
it('can retrieve a profile from the web and save it to state', async function () {
const hash = 'c5e53f9ab6aecef926d4be68c84f2de550e2ac2f';
const expectedUrl = `https://storage.googleapis.com/profile-store/${hash}`;
window.fetch.get(
expectedUrl,
makeProfileSerializable(_getSimpleProfile())
);
const store = blankStore();