-
Notifications
You must be signed in to change notification settings - Fork 110
/
dist.js
1907 lines (1804 loc) · 67.4 KB
/
dist.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
var gInitialPageState = null;
var gFilterChangeTimeout = null;
var gCurrentHistogramsList = null;
var gCurrentDates = null;
var gCurrentMinDate = null,
gCurrentMaxDate = null;
var gFilters;
var gPreviousFilterAllSelected = {};
var gAxesList;
var gAxesSelectors;
var gNoneKey = "__none__";
indicate("Initializing Telemetry...");
$(function () {
Telemetry.init(function () {
gFilters = {
"application": $("#filter-product"),
"os": $("#filter-os"),
"architecture": $("#filter-arch"),
"child": $("#filter-process-type"),
};
gAxesList = [
$("#distribution1")
.get(0), $("#distribution2")
.get(0),
$("#distribution3")
.get(0), $("#distribution4")
.get(0),
];
gAxesSelectors = [
$("#selected-key1"),
$("#selected-key2"),
$("#selected-key3"),
$("#selected-key4"),
]
gInitialPageState = loadStateFromUrlAndCookie();
// If we don't have release versions and the page state is for release,
// trigger an authorization failure flow
let maxIsRelease = gInitialPageState.max_channel_version &&
gInitialPageState.max_channel_version.startsWith("release/");
if (maxIsRelease &&
typeof Telemetry.AuthorizationFailed === "function" &&
!Telemetry.getVersions().filter(cv => cv.startsWith("release/")).length
) {
// Persist state to cookie so it can survive the auth flow.
saveStateStringToCookie(buildStateString(gInitialPageState));
Telemetry.AuthorizationFailed();
}
// Set up settings selectors
multiselectSetOptions($("#channel-version"),
getHumanReadableOptions("channelVersion", Telemetry.getVersions())
);
if (gInitialPageState.max_channel_version !== undefined) {
if (gInitialPageState.max_channel_version === null) { // No version selected, select the latest nightly
var nightlyVersions = Telemetry.getVersions()
.filter(function (channelVersion) {
return channelVersion.startsWith("nightly/");
})
.sort();
gInitialPageState.max_channel_version = nightlyVersions[
nightlyVersions.length - 1];
}
$("#channel-version")
.next()
.find("input[type=radio]")
.attr("checked", false);
$("#channel-version")
.multiselect("select", gInitialPageState.max_channel_version);
}
if (gInitialPageState.compare !== undefined) {
$("#compare")
.multiselect("select", gInitialPageState.compare);
}
// Initialize setting values from the page state
$("#sort-keys")
.multiselect("select", gInitialPageState.sort_keys);
$("input[name=table-toggle]")
.prop("checked", gInitialPageState.table !== 0)
.trigger("change");
$("input[name=cumulative-toggle]")
.prop("checked", gInitialPageState.cumulative !== 0)
.trigger("change");
$("input[name=trim-toggle]")
.prop("checked", gInitialPageState.trim !== 0)
.trigger("change");
$("input[name=build-time-toggle]")
.prop("checked", gInitialPageState.use_submission_date !== 0)
.trigger("change");
$("input[name=sanitize-toggle]")
.prop("checked", gInitialPageState.sanitize !== 0)
.trigger("change");
$("input[name=include-spill-toggle]")
.prop("checked", gInitialPageState.include_spill > 0)
.trigger("change");
$("input[name=sort-by-value]")
.prop("checked", gInitialPageState.sort_by_value > 0)
.trigger("change");
updateOptions(function () {
if (gInitialPageState.product !== null) {
$("#filter-product")
.multiselect("select", gInitialPageState.product);
} else {
$("#filter-product")
.multiselect("selectAll", false)
.multiselect("updateButtonText");
}
if (gInitialPageState.arch !== null) {
$("#filter-arch")
.multiselect("select", gInitialPageState.arch);
} else {
$("#filter-arch")
.multiselect("selectAll", false)
.multiselect("updateButtonText");
}
if (gInitialPageState.processType !== null) {
$("#filter-process-type")
.multiselect("select", gInitialPageState.processType);
} else {
$("#filter-process-type")
.multiselect("select", "*")
.multiselect("updateButtonText");
}
if (gInitialPageState.os !== null) { // We accept values such as "WINNT", as well as "WINNT,6.1"
$("#filter-os")
.multiselect("select", expandOSs(gInitialPageState.os));
} else {
$("#filter-os")
.multiselect("selectAll", false)
.multiselect("updateButtonText");
}
for (var filterName in gFilters) {
var selector = gFilters[filterName];
if (["filter-product", "filter-os"].indexOf(selector.attr(
"id")) >= 0) { // Only apply the select all change to the product and OS selector
var selected = selector.val() || [],
options = selector.find("option");
gPreviousFilterAllSelected[selector.attr("id")] =
selected.length === options.length;
}
}
$("#channel-version")
.change(function () {
updateOptions(function () {
$("#measure")
.trigger("change");
});
});
$([
"input[name=build-time-toggle]",
"input[name=sanitize-toggle]",
"#sort-keys",
"#measure",
"#filter-product",
"#filter-os",
"#filter-arch",
"#filter-process-type",
"#compare",
].join(",")).change(function (e) {
var $this = $(this);
if (gFilterChangeTimeout !== null) {
clearTimeout(gFilterChangeTimeout);
}
gFilterChangeTimeout = setTimeout(function () { // Debounce the changes to prevent rapid filter changes from causing too many updates
if (["filter-product", "filter-os"].indexOf($this
.attr("id")) >= 0) { // Only apply the select all change to the product and OS selector
// If options (but not all options) were deselected when previously all options were selected, invert selection to include only those deselected
var selected = $this.val() || [],
options = $this.find("option");
if (selected.length !== options.length &&
selected.length > 0 &&
gPreviousFilterAllSelected[$this.attr("id")]) {
var nonSelectedOptions = options.map(function (
i, option) {
return option.getAttribute("value");
})
.toArray()
.filter(function (filterOption) {
return selected.indexOf(filterOption) <
0;
});
$this.multiselect("deselectAll")
.multiselect("select", nonSelectedOptions);
}
gPreviousFilterAllSelected[$this.attr("id")] =
selected.length === options.length; // Store state
}
updateOSs();
calculateHistograms(function (histogramsMap,
evolutionsMap) {
// histogramsMap is a mapping from keyed histogram keys (or "" if not a keyed histogram) to lists of histograms (one per comparison option, so each histogram in a list has the same buckets)
// evolutionsMap is a mapping from keyed histogram keys (or "" if not a keyed histogram) to lists of evolutions (one per comparison option, so each evolution in a list has the same dates)
// Get the set union of all the dates in all the evolutions
var datesMap = {};
for (var label in evolutionsMap) {
evolutionsMap[label][0].dates()
.forEach(function (date) {
datesMap[date.getTime()] = true;
});
}
gCurrentDates = Object.keys(datesMap)
.map(function (dateString) {
return new Date(parseInt(dateString));
})
.sort(function (a, b) {
return a - b;
});
// Set up key selectors, selecting the previously selected key if it still exists and the first key otherwise
var getAggregate = { // Function to get an aggregate for a list of histograms, used for sorting later
"submissions": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.count;
}, 0);
},
"mean": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.mean();
}, 0) / histograms.length;
},
"5th-percentile": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.percentile(
5);
}, 0) / histograms.length;
},
"25th-percentile": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.percentile(
25);
}, 0) / histograms.length;
},
"median": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.percentile(
50);
}, 0) / histograms.length;
},
"75th-percentile": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.percentile(
75);
}, 0) / histograms.length;
},
"95th-percentile": function (histograms) {
return histograms.reduce(function (
total, histogram) {
return total + histogram.percentile(
95);
}, 0) / histograms.length;
},
}[$("#sort-keys")
.val()];
if (getAggregate === undefined) {
throw "Could not obtain aggregate function"
};
gCurrentHistogramsList = Object.keys(
histogramsMap)
.map(function (label) {
return {
title: label,
histograms: histogramsMap[label]
};
})
.sort(function (entry1, entry2) { // Sort by the desired aggregate
return getAggregate(entry2.histograms) -
getAggregate(entry1.histograms);
});
var keys = gCurrentHistogramsList.map(
function (entry) {
return entry.title;
});
var options = getHumanReadableOptions("key",
keys);
gAxesSelectors.forEach(function (selector,
i) {
multiselectSetOptions(selector,
options.concat([[gNoneKey,
"(none)"]]));
// If the recalculation was done as a result of resorting keys, reset the keys to the top 4
if ($this.attr("id") === "sort-keys") {
gInitialPageState.keys = options.map(
function (option) {
return option[0]
})
.filter(function (value, i) {
return i < 4;
});
}
// There is a bug in bootstrap-multiselect where, upon selection when existing items are selected,
// the existing item's radio button does not become deselected - we work around this by manually clearing
// all the buttons, which works pretty well
selector.multiselect("deselectAll",
false)
.next()
.find("input[type=radio]")
.attr("checked", false);
// Select i-th key if possible, otherwise none
if (i < options.length) {
selector.multiselect("select",
options[i][0]);
} else {
selector.multiselect("select",
gNoneKey);
}
});
if (gInitialPageState.keys) { // Reselect previously selected keys
gInitialPageState.keys.forEach(function (
key, i) {
if (key !== gNoneKey) {
// Check to make sure the key can actually still be selected
if (gAxesSelectors[i].find(
"option")
.filter(function (i, option) {
return $(option)
.val() === key;
})
.length > 0) {
gAxesSelectors[i].next()
.find("input[type=radio]")
.attr("checked", false);
gAxesSelectors[i].multiselect(
"select", key);
}
}
});
}
$("#selected-key1")
.trigger("change");
}, $("input[name=sanitize-toggle]")
.is(":checked"));
}, 0);
});
$(
"#selected-key1, #selected-key2, #selected-key3, #selected-key4, input[name=table-toggle], input[name=cumulative-toggle], input[name=trim-toggle], input[name=include-spill-toggle], input[name=sort-by-value]"
)
.change(function (e) {
if (gCurrentHistogramsList.length > 1) { // Keyed histogram with multiple keys, find the selected keys
var histogramsList = [];
var keys = gAxesSelectors.forEach(function (selector,
i) {
var key = $(selector)
.val();
if (key === gNoneKey) {
histogramsList.push({
title: "",
histograms: []
});
} else {
gCurrentHistogramsList.forEach(function (
entry) {
if (entry.title === key) {
histogramsList.push(entry);
}
});
}
});
} else { // Non-keyed histogram or a keyed histogram with only one key
var histogramsList = makenewHistogramListCopy(gCurrentHistogramsList);
}
displayHistograms(histogramsList, gCurrentDates,
$("input[name=table-toggle]").is(':checked'),
$("input[name=cumulative-toggle]").is(':checked'),
$("input[name=trim-toggle]").is(':checked'),
$("input[name=include-spill-toggle]").is(':checked'),
$("input[name=sort-by-value]").is(':checked')
);
saveStateToUrlAndCookie();
});
// Perform a full display refresh
$("#measure")
.trigger("change");
});
var resizeUpdateTimeout = null;
$(window)
.resize(function () {
// Automatically resize range bar
var dateControls = $("#date-range-controls");
$("#range-bar")
.outerWidth(dateControls.parent()
.width() - dateControls.outerWidth() - 10);
// Resize the main plot (MetricsGraphics has a full_width option, but that breaks zooming for plots)
if (resizeUpdateTimeout !== null) {
clearTimeout(resizeUpdateTimeout);
}
resizeUpdateTimeout = setTimeout(function () {
$("#selected-key1")
.trigger("change");
}, 50);
});
$("#advanced-settings")
.on("shown.bs.collapse", function () {
var dateControls = $("#date-range-controls");
$("#range-bar")
.outerWidth(dateControls.parent()
.width() - dateControls.outerWidth() - 10);
$(this)
.get(0)
.scrollIntoView({
behavior: "smooth"
}); // Scroll the advanced settings into view when opened
});
});
});
function updateOptions(callback) {
var channelVersion = $("#channel-version")
.val();
var parts = channelVersion.split("/"); //wip: clean this up
indicate("Updating options...");
var operation = asyncOperationCheck("updateOptions");
Telemetry.getFilterOptions(parts[0], parts[1], function (optionsMap) {
if (asyncOperationWasInterrupted("updateOptions", operation)) { // Don't call callback if this isn't the latest invocation of the function
return;
}
multiselectSetOptions($("#measure"), getHumanReadableOptions("measure",
deduplicate(optionsMap.metric || []).concat(gInitialPageState.measure)));
$("#measure")
.multiselect("select", gInitialPageState.measure);
multiselectSetOptions($("#filter-product"), getHumanReadableOptions(
"application", deduplicate(optionsMap.application || [])));
multiselectSetOptions($("#filter-arch"), getHumanReadableOptions(
"architecture", deduplicate(optionsMap.architecture || [])));
multiselectSetOptions($("#filter-process-type"),
getHumanReadableOptions("child", deduplicate(optionsMap.child || []))
);
// Compressing and expanding the OSs also has the effect of making OSs where all the versions were selected also all selected in the new one, regardless of whether those versions were actually in common or not
var selectedOSs = compressOSs();
multiselectSetOptions($("#filter-os"), getHumanReadableOptions("os",
deduplicate(optionsMap.os || [])));
$("#filter-os")
.multiselect("select", expandOSs(selectedOSs));
if (callback !== undefined) {
indicate();
callback();
}
});
}
function calculateHistograms(callback, sanitize) {
// Get selected version, measure, and aggregate options
var channelVersion = $("#channel-version")
.val();
var measure = $("#measure")
.val();
var comparisonName = $("#compare")
.val();
var filterSetsMapping = getFilterSetsMapping(gFilters, comparisonName !== "" ?
comparisonName : null); // Mapping from option values to lists of filter sets
var totalFilters = 0;
for (var option in filterSetsMapping) {
totalFilters += filterSetsMapping[option].length;
}
if (totalFilters === 0 || measure === null) { // No filters selected, or no measures available, so no histograms could be created
indicate();
updateDateRange(function (dates) {
callback({}, {});
}, [], false);
return;
}
var useSubmissionDate = $("input[name=build-time-toggle]").is(":checked");
var fullEvolutionsMap = {}; // Mapping from labels (the keys in keyed histograms) to lists of combined filtered evolutions (one per comparison option, combined from all filter sets in that option)
var optionValues = {}; // Map from labels to lists of options in the order that they were done being processed, rather than the order they appeared in
var filterSetsCount = 0,
totalFiltersCount = 0;
var filterSetsMappingOptions = Object.keys(filterSetsMapping);
var operation = asyncOperationCheck("calculateHistograms");
filterSetsMappingOptions.forEach(function (filterSetsMappingOption, i) { // For each option being compared by
var filterSets = filterSetsMapping[filterSetsMappingOption];
var filtersCount = 0,
fullEvolutionMap = {};
indicate("Updating histograms...");
filterSets.forEach(function (filterSet) {
var parts = channelVersion.split("/");
Telemetry.getEvolution(parts[0], parts[1], measure, filterSet,
useSubmissionDate,
function (evolutionMap) {
if (asyncOperationWasInterrupted("calculateHistograms",
operation)) { // Don't call callback if this isn't the latest invocation of the function
return;
}
totalFiltersCount++;
filtersCount++;
indicate("Updating histograms... ", 100 * totalFiltersCount /
totalFilters);
for (var label in evolutionMap) {
if (fullEvolutionMap.hasOwnProperty(label)) {
fullEvolutionMap[label] = fullEvolutionMap[label].combine(
evolutionMap[label]);
} else {
fullEvolutionMap[label] = evolutionMap[label];
}
}
if (filtersCount === filterSets.length) { // Check if we have loaded all the needed filters in the current filter set
filterSetsCount++;
for (var label in fullEvolutionMap) { // Make a list of evolutions and option labels for each label in the evolution
if (sanitize) {
fullEvolutionMap[label] = fullEvolutionMap[label].sanitized();
}
if (!fullEvolutionMap[label]) {
continue; // data was sanitized away. Move along.
}
if (!fullEvolutionsMap.hasOwnProperty(label)) {
fullEvolutionsMap[label] = [];
}
if (fullEvolutionMap[label] !== null) {
fullEvolutionsMap[label].push(fullEvolutionMap[label]);
}
if (!optionValues.hasOwnProperty(label)) {
optionValues[label] = [];
}
optionValues[label].push(filterSetsMappingOption); // Add the current option value being compared by
}
if (filterSetsCount === filterSetsMappingOptions.length) { // Check if we have loaded all the filter set collections
indicate();
// Get the set union of all the dates in all the evolutions
var datesMap = {};
for (var label in fullEvolutionsMap) {
if (fullEvolutionsMap[label].length > 0) {
fullEvolutionsMap[label][0].dates()
.forEach(function (date) {
datesMap[date.getTime()] = true;
});
}
}
var dates = Object.keys(datesMap)
.map(function (dateString) {
return new Date(parseInt(dateString));
})
.sort(function (a, b) {
return a - b;
});
updateDateRange(function (dates) {
if (dates == null) { // No dates in the selected range, so no histograms available
callback({}, {});
} else { // Filter the evolution to include only those histograms that are in the selected range
var filteredEvolutionsMap = {},
filteredHistogramsMap = {};
for (var label in fullEvolutionsMap) {
var filteredEntries = fullEvolutionsMap[label]
.map(function (evolution, i) {
return {
option: optionValues[label][i],
evolution: evolution.dateRange(dates[
0], dates[dates.length - 1])
}; // We don't need to worry about this returning null since the dates came from the evolution originally
})
.filter(function (entry) {
return entry.evolution !== null;
});
var filteredEvolutions = filteredEntries.map(
function (entry) {
return entry.evolution;
});
var filteredOptionValues = filteredEntries.map(
function (entry) {
return entry.option;
});
if (filteredEvolutions.length > 0) { // There are evolutions in this date
filteredEvolutionsMap[label] =
filteredEvolutions;
filteredHistogramsMap[label] =
filteredEvolutions.map(function (
evolution, i) {
var histogram = evolution.histogram();
if (comparisonName !== "") { // We are comparing by an option value
var humanReadableOption =
getHumanReadableOptions(
comparisonName, [
filteredOptionValues[i]])[0][
1];
histogram.measure =
humanReadableOption;
}
return histogram;
})
.sort(function (histogram1, histogram2) {
return histogram1.measure <
histogram2.measure ?
-1 : (histogram1.measure >
histogram2.measure ? 1 : 0);
});
}
}
callback(filteredHistogramsMap,
filteredEvolutionsMap);
}
}, dates, false);
}
}
});
});
});
}
var gLastTimeoutID = null;
var gLoadedDateRangeFromState = false;
var gCurrentDateRangeUpdateCallback = null; // This is used by the date range slider so we dispatch the correct callback even if we aren't updating the date range
var gPreviousMinMoment = null,
gPreviousMaxMoment = null;
function updateDateRange(callback, dates, updatedByUser, shouldUpdateRangebar) { // dates is null for when there are no evolutions
shouldUpdateRangebar = shouldUpdateRangebar === undefined ? true :
shouldUpdateRangebar;
gCurrentDateRangeUpdateCallback = callback || function () {};
if (dates.length === 0) {
$("#date-range")
.prop("disabled", true);
$("#range-bar")
.hide();
gCurrentDateRangeUpdateCallback(null);
return;
}
$("#date-range")
.prop("disabled", false);
$("#range-bar")
.show();
var timeCutoff = moment.utc()
.add(1, "years")
.toDate()
.getTime();
if (dates[dates.length - 1] > timeCutoff) {
dates = dates.filter(function (date) {
return date < timeCutoff
});
}
var minMoment = moment.utc(dates[0])
.format("YYYY-MM-DD"),
maxMoment = moment.utc(dates[dates.length - 1])
.format("YYYY-MM-DD");
gCurrentMinDate = minMoment, gCurrentMaxDate = maxMoment;
// Update the start and end range and update the selection if necessary
var picker = $("#date-range")
.data("daterangepicker");
picker.setOptions({
format: "YYYY/MM/DD",
minDate: minMoment,
maxDate: maxMoment,
showDropdowns: true,
drops: "up",
opens: "center",
ranges: {
"All": [minMoment, maxMoment],
"Last 30 days of data": [moment.utc(maxMoment)
.subtract(30, "days")
.format("YYYY-MM-DD"), endMoment],
"Last 7 days of data": [moment.utc(maxMoment)
.subtract(6, "days")
.format("YYYY-MM-DD"), endMoment],
},
}, function (chosenStartMoment, chosenEndMoment, label) {
updateDateRange(gCurrentDateRangeUpdateCallback, dates, true);
});
// First load, update the date picker from the page state
if (!gLoadedDateRangeFromState && gInitialPageState.start_date !== null &&
gInitialPageState.end_date !== null) {
gLoadedDateRangeFromState = true;
var startMoment = gInitialPageState.start_date,
endMoment = gInitialPageState.end_date;
if (moment.utc(startMoment)
.isValid() && moment.utc(endMoment)
.isValid()) {
picker.setStartDate(startMoment);
picker.setEndDate(endMoment);
gPreviousMinMoment = minMoment;
gPreviousMaxMoment = maxMoment;
}
// If advanced settings are not at their defaults, expand the settings pane on load
var isKeyedHistogram = $("#sort-keys-option").css("display") !== "none";
if (gInitialPageState.use_submission_date !== 0 || gInitialPageState.table !==
0 || gInitialPageState.cumulative !== 0 || gInitialPageState.trim !== 1 ||
(isKeyedHistogram && gInitialPageState.sort_keys !== "submissions") ||
startMoment !== minMoment || endMoment !== maxMoment) {
$("#advanced-settings-toggle")
.click();
}
}
// If the selected date range is now out of bounds, or the bounds were updated programmatically and changed, select the entire range
var pickerStartDate = picker.startDate.format("YYYY-MM-DD");
var pickerEndDate = picker.endDate.format("YYYY-MM-DD");
if (pickerStartDate > maxMoment || pickerStartDate < minMoment ||
pickerEndDate > maxMoment || pickerEndDate < minMoment ||
(!updatedByUser && (minMoment !== gPreviousMinMoment || maxMoment !==
gPreviousMaxMoment))) {
picker.setStartDate(minMoment);
picker.setEndDate(maxMoment);
pickerStartDate = minMoment;
pickerEndDate = maxMoment;
}
gPreviousMinMoment = minMoment;
gPreviousMaxMoment = maxMoment;
// Rebuild rangebar if it was changed by something other than the user
if (shouldUpdateRangebar) {
var rangeBarControl = RangeBar({
min: minMoment,
max: moment(maxMoment)
.add(1, "days")
.format("YYYY-MM-DD"),
maxRanges: 1,
valueFormat: function (ts) {
return ts;
},
valueParse: function (date) {
return moment.utc(date)
.valueOf();
},
label: function (a) {
var days = (a[1] - a[0]) / 86400000;
return days < 5 ? days : moment.utc(a[1])
.from(a[0], true);
},
snap: 1000 * 60 * 60 * 24,
minSize: 1000 * 60 * 60 * 24,
bgLabels: 0,
})
.on("changing", function (e, ranges, changed) {
var range = ranges[0];
if (gLastTimeoutID !== null) {
clearTimeout(gLastTimeoutID);
}
gLastTimeoutID = setTimeout(function () { // Debounce slider movement callback
picker.setStartDate(moment.utc(range[0])
.format("YYYY-MM-DD"))
picker.setEndDate(moment.utc(range[1])
.subtract(1, "days")
.format("YYYY-MM-DD"));
updateDateRange(gCurrentDateRangeUpdateCallback, dates, true,
false);
}, 50);
});
$("#range-bar")
.empty()
.append(rangeBarControl.$el);
var dateControls = $("#date-range-controls");
$("#range-bar")
.outerWidth(dateControls.parent()
.width() - dateControls.outerWidth() - 10);
rangeBarControl.val([[moment(pickerStartDate)
.toDate(), moment(pickerEndDate)
.add(1, "days")
.toDate()]]);
}
var min = moment.utc(pickerStartDate)
.toDate(),
max = moment.utc(pickerEndDate)
.toDate();
var filteredDates = dates.filter(function (date) {
return min <= date && date <= max;
});
if (filteredDates.length == 0) {
if (dates.length === 0) {
$("#date-range")
.prop("disabled", true);
$("#range-bar")
.hide();
}
gCurrentDateRangeUpdateCallback(null);
} else {
gCurrentDateRangeUpdateCallback(filteredDates);
}
}
function displayHistograms(histogramsList, dates, useTable, cumulative, trim, includeSpill, sortByValue) {
cumulative = cumulative === undefined ? false : cumulative;
trim = trim === undefined ? true : trim;
// Hide the 'spill' bucket if present
if (!includeSpill && histogramsList.length) {
const spillIndex = histogramsList[0].histograms[0].buckets.indexOf("spill");
histogramsList[0].histograms[0].buckets = histogramsList[0].histograms[0].buckets
.filter((value, index) => index !== spillIndex);
histogramsList[0].histograms[0].values = histogramsList[0].histograms[0].values
.filter((value, index) => index !== spillIndex);
}
var minTrimLeft = 0,
minTrimRight = 0,
maxPercentage = 0;
histogramsList.forEach(function (entry) { // Find the largest percentage on the graph to determine the upper bound for all the graphs
if (cumulative) {
maxPercentage = 100;
} // Cumulative histograms always have a max percentage of 100%
else {
entry.histograms.forEach(function (histogram) {
histogram.map(function (count, start, end, i) {
if (100 * count / histogram.count > maxPercentage) {
maxPercentage = 100 * count / histogram.count;
}
});
});
}
});
if (trim) { // Figure out how much to trim buckets on both ends in the histogram if their counts are too low
// Histograms must have at least 3 buckets to render properly, so ensure that we don't trim them too much
minTrimLeft = Infinity;
minTrimRight = Infinity;
histogramsList.forEach(function (entry) {
if (entry.histograms.length === 0) { // No histograms, don't consider it in the trimming calculation
return;
}
var trimLeft = 0,
trimRight = 0;
var countsList = entry.histograms.map(function (histogram) {
return histogram.map(function (count, start, end, i) {
return count;
});
});
if (cumulative) { // Show cumulative histogram by adding up all the previous data points
countsList = countsList.map(function (counts) {
var total = 0;
return counts.map(function (count) {
return total += count;
});
});
}
var countList = countsList[0].map(function (count) {
return 0;
});
countsList.forEach(function (counts) {
counts.forEach(function (count, i) {
countList[i] += count;
});
});
var total = countList.reduce(function (total, count) {
return total + count;
}, 0);
var countCutoff = total * 0.0001; // Set the samples cutoff to 0.01% of the total samples
while (countList[trimLeft] < countCutoff && countList.length -
trimLeft - trimRight > 3) {
trimLeft++;
}
while (countList[countList.length - 1 - trimRight] < countCutoff &&
countList.length - trimLeft - trimRight > 3) {
trimRight++;
}
if (trimLeft < minTrimLeft) {
minTrimLeft = trimLeft;
}
if (trimRight < minTrimRight) {
minTrimRight = trimRight;
}
});
}
if (histogramsList.length > 0 && histogramsList[0].histograms.length > 0) {
// Set the histogram caption to the histogram description
var description = histogramsList[0].histograms[0].description
var metric = histogramsList[0].histograms[0].measure
var channel = $("#channel-version").val().split("/")[0]
var desc = getDescription(metric, channel, description);
var link = getDescriptionLink(metric, channel, description);
if (metric != desc) {
$('#dist-caption-text').html(desc);
} else {
$('#dist-caption-text').text("");
}
$('#dist-caption-link').html(link);
var useCounterLink = getUseCounterLink(metric, channel, description);
$('#use-counter-link').html(useCounterLink);
} else {
$('#dist-caption-text').text(""); // Clear the histogram caption
$('#dist-caption-link').text(""); // Clear the histogram link
$('#use-counter-link').text(""); // Clear the use counter link
}
if (histogramsList.length <= 1) { // Only one histograms set
if (histogramsList.length === 1 && histogramsList[0].histograms.length ===
1) { // Only show one set of axes
var histogram = histogramsList[0].histograms[0];
if (histogram.kind == 'categorical' && sortByValue) {
let sorting = [];
for (let index = 0; index < histogram.buckets.length; index++) {
sorting.push([histogram.values[index], histogram.buckets[index]]);
}
sorting.sort((a, b) => b[0] - a[0] || a[1].localeCompare(b[1]));
histogram.values = sorting.map(x => x[0]);
histogram.buckets = sorting.map(x => x[1]);
}
$("#prop-kind")
.text(histogram.kind);
$("#prop-dates")
.text(formatNumber(dates.length));
$("#prop-date-range")
.text(moment.utc(dates[0])
.format("YYYY/MM/DD") + ((dates.length == 1) ? "" : " to " + moment.utc(
dates[dates.length - 1])
.format("YYYY/MM/DD")));
$("#prop-submissions")
.text(formatNumber(histogram.submissions));
$("#prop-count")
.text(formatNumber(histogram.count));
$("#prop-sum")
.text(formatNumber(histogram.sum));
if (histogram.kind == "linear" || histogram.kind == "exponential") {
$("#prop-p5")
.text(formatNumber(histogram.percentile(5)));
$("#prop-p25")
.text(formatNumber(histogram.percentile(25)));
$("#prop-p50")
.text(formatNumber(histogram.percentile(50)));
$("#prop-p75")
.text(formatNumber(histogram.percentile(75)));
$("#prop-p95")
.text(formatNumber(histogram.percentile(95)));
$(".scalar-only")
.show();
} else {
$(".scalar-only")
.hide();
}
$("#summary")
.show();
$("#stats-comparison")
.hide();
} else {
let histogramPercentiles = $("#histogram-percentiles");
histogramPercentiles.empty();
if (histogramsList.length > 0) {
histogramPercentiles.append(
histogramsList[0].histograms.map(function(histogram) {
return `<tr>
<th>${histogram.measure}</th>
<td>${formatNumber(histogram.percentile(5))}</td>
<td>${formatNumber(histogram.percentile(25))}</td>
<td>${formatNumber(histogram.percentile(50))}</td>
<td>${formatNumber(histogram.percentile(75))}</td>
<td>${formatNumber(histogram.percentile(95))}</td>
</tr>`;
})
);
}
$("#summary")
.hide();
$("#stats-comparison")
.show();
}
$("#plots")
.removeClass("col-md-11")
.addClass("col-md-9");
gAxesList.forEach(function (axes) {
$(axes)
.parent()
.parent()
.hide();
});
$(gAxesList[0])