/
performance-impl.js
918 lines (821 loc) · 27.4 KB
/
performance-impl.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
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Deferred} from '../utils/promise';
import {Services} from '../services';
import {VisibilityState} from '../visibility-state';
import {dev} from '../log';
import {dict, map} from '../utils/object';
import {getMode} from '../mode';
import {getService, registerServiceBuilder} from '../service';
import {isStoryDocument} from '../utils/story';
import {layoutRectLtwh} from '../layout-rect';
import {throttle} from '../utils/rate-limit';
import {whenContentIniLoad} from '../ini-load';
import {whenDocumentComplete, whenDocumentReady} from '../document-ready';
/**
* Maximum number of tick events we allow to accumulate in the performance
* instance's queue before we start dropping those events and can no longer
* be forwarded to the actual `tick` function when it is set.
*/
const QUEUE_LIMIT = 50;
/** @const {string} */
const VISIBILITY_CHANGE_EVENT = 'visibilitychange';
/**
* Fields:
* {{
* label: string,
* delta: (number|null|undefined),
* value: (number|null|undefined)
* }}
* @typedef {!JsonObject}
*/
let TickEventDef;
/**
* Increments the value, else defaults to 0 for the given object key.
* @param {!Object<string, (string|number|boolean|Array|Object|null)>} obj
* @param {?string} name
*/
function incOrDef(obj, name) {
if (!name) {
return;
}
if (!obj[name]) {
obj[name] = 1;
} else {
obj[name]++;
}
}
/**
* Performance holds the mechanism to call `tick` to stamp out important
* events in the lifecycle of the AMP runtime. It can hold a small amount
* of tick events to forward to the external `tick` function when it is set.
*/
export class Performance {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const {!Window} */
this.win = win;
/** @private @const {number} */
this.initTime_ = this.win.Date.now();
/** @const @private {!Array<TickEventDef>} */
this.events_ = [];
/** @private {?./ampdoc-impl.AmpDoc} */
this.ampdoc_ = null;
/** @private {?./viewer-interface.ViewerInterface} */
this.viewer_ = null;
/** @private {?./resources-interface.ResourcesInterface} */
this.resources_ = null;
/** @private {boolean} */
this.isMessagingReady_ = false;
/** @private {boolean} */
this.isPerformanceTrackingOn_ = false;
/** @private {!Object<string,boolean>} */
this.enabledExperiments_ = map();
/** @private {string} */
this.ampexp_ = '';
this.fcpDeferred_ = new Deferred();
this.fvrDeferred_ = new Deferred();
this.mbvDeferred_ = new Deferred();
// Platform service must be installed before performance serivce is
this.platform_ = Services.platformFor(this.win);
// TODO (micajuineho) change this once all platforms
// support PerformancePaintTiming
// https://developer.mozilla.org/en-US/docs/Web/API/PerformancePaintTiming
if (!this.platform_.isChrome() && !this.platform_.isOpera()) {
this.fcpDeferred_.resolve(null);
}
/**
* How many times a layout jank metric has been ticked.
*
* @private {number}
*/
this.jankScoresTicked_ = 0;
/**
* How many times a layout shift metric has been ticked.
*
* @private {number}
*/
this.shiftScoresTicked_ = 0;
/**
* The sum of all layout jank fractions triggered on the page from the
* Layout Jank API.
*
* @private {number}
*/
this.aggregateJankScore_ = 0;
/**
* The sum of all layout shift fractions triggered on the page from the
* Layout Instability API.
*
* @private {number}
*/
this.aggregateShiftScore_ = 0;
/**
* Whether the user agent supports the Layout Instability API that shipped
* with Chrome 76.
*
* @private {boolean}
*/
this.supportsLayoutInstabilityAPIv76_ = false;
/**
* Whether the user agent supports the Layout Instability API that shipped
* with Chrome 77.
*
* @private {boolean}
*/
this.supportsLayoutInstabilityAPIv77_ = false;
/**
* Whether the user agent supports the Event Timing API that shipped
* with Chrome 76.
*
* @private {boolean}
*/
this.supportsEventTimingAPIv76_ = false;
/**
* Whether the user agent supports the Event Timing API that shipped
* with Chrome 77.
*
* @private {boolean}
*/
this.supportsEventTimingAPIv77_ = false;
/**
* Whether the user agent supports the Largest Contentful Paint metric.
*
* @private {boolean}
*/
this.supportsLargestContentfulPaint_ = false;
const {PerformanceObserver} = this.win;
if (PerformanceObserver) {
const {supportedEntryTypes} = PerformanceObserver;
if (supportedEntryTypes) {
this.supportsLayoutInstabilityAPIv76_ = this.win.PerformanceObserver.supportedEntryTypes.includes(
'layoutShift'
);
this.supportsLayoutInstabilityAPIv77_ = this.win.PerformanceObserver.supportedEntryTypes.includes(
'layout-shift'
);
this.supportsEventTimingAPIv76_ = this.win.PerformanceObserver.supportedEntryTypes.includes(
'firstInput'
);
this.supportsEventTimingAPIv77_ = this.win.PerformanceObserver.supportedEntryTypes.includes(
'first-input'
);
this.supportsLargestContentfulPaint_ = this.win.PerformanceObserver.supportedEntryTypes.includes(
'largest-contentful-paint'
);
}
}
/**
* The latest reported largest contentful paint time, where the loadTime
* is specified.
*
* @private {number|null}
*/
this.largestContentfulPaintLoadTime_ = null;
/**
* The latest reported largest contentful paint time, where the renderTime
* is specified.
*
* @private {number|null}
*/
this.largestContentfulPaintRenderTime_ = null;
this.boundOnVisibilityChange_ = this.onVisibilityChange_.bind(this);
this.onAmpDocVisibilityChange_ = this.onAmpDocVisibilityChange_.bind(this);
// Add RTV version as experiment ID, so we can slice the data by version.
this.addEnabledExperiment('rtv-' + getMode(this.win).rtvVersion);
// Tick document ready event.
whenDocumentReady(win.document).then(() => {
this.tick('dr');
this.flush();
});
// Tick window.onload event.
whenDocumentComplete(win.document).then(() => this.onload_());
this.registerPerformanceObserver_();
this.registerFirstInputDelayPolyfillListener_();
}
/**
* Listens to viewer and resource events.
* @return {!Promise}
*/
coreServicesAvailable() {
const {documentElement} = this.win.document;
this.ampdoc_ = Services.ampdoc(documentElement);
this.viewer_ = Services.viewerForDoc(documentElement);
this.resources_ = Services.resourcesForDoc(documentElement);
this.isPerformanceTrackingOn_ =
this.viewer_.isEmbedded() && this.viewer_.getParam('csi') === '1';
// This is for redundancy. Call flush on any visibility change.
this.ampdoc_.onVisibilityChanged(this.flush.bind(this));
// Does not need to wait for messaging ready since it will be queued
// if it isn't ready.
this.measureUserPerceivedVisualCompletenessTime_();
// Can be null which would mean this AMP page is not embedded
// and has no messaging channel.
const channelPromise = this.viewer_.whenMessagingReady();
this.ampdoc_.whenFirstVisible().then(() => {
this.tick('ofv');
this.flush();
});
const registerVisibilityChangeListener =
this.win.PerformanceLayoutJank ||
this.supportsLargestContentfulPaint_ ||
this.supportsLayoutInstabilityAPIv76_ ||
this.supportsLayoutInstabilityAPIv77_;
// Register a handler to record metrics when the page enters the hidden
// lifecycle state.
if (registerVisibilityChangeListener) {
this.win.addEventListener(
VISIBILITY_CHANGE_EVENT,
this.boundOnVisibilityChange_,
{capture: true}
);
this.ampdoc_.onVisibilityChanged(this.onAmpDocVisibilityChange_);
}
// We don't check `isPerformanceTrackingOn` here since there are some
// events that we call on the viewer even though performance tracking
// is off we only need to know if the AMP page has a messaging
// channel or not.
if (!channelPromise) {
return Promise.resolve();
}
return channelPromise
.then(() => {
// Tick the "messaging ready" signal.
this.tickDelta('msr', this.win.Date.now() - this.initTime_);
// Tick timeOrigin so that epoch time can be calculated by consumers.
this.tickDelta(
'timeOrigin',
this.win.performance.timeOrigin ||
this.win.performance.timing.navigationStart
);
return this.maybeAddStoryExperimentId_();
})
.then(() => {
this.isMessagingReady_ = true;
// Forward all queued ticks to the viewer since messaging
// is now ready.
this.flushQueuedTicks_();
// Send all csi ticks through.
this.flush();
});
}
/**
* Add a story experiment ID in order to slice the data for amp-story.
* @return {!Promise}
* @private
*/
maybeAddStoryExperimentId_() {
const ampdoc = Services.ampdocServiceFor(this.win).getSingleDoc();
return isStoryDocument(ampdoc).then(isStory => {
if (isStory) {
this.addEnabledExperiment('story');
}
});
}
/**
* Callback for onload.
*/
onload_() {
this.tick('ol');
this.tickLegacyFirstPaintTime_();
this.flush();
}
/**
* Reports performance metrics first paint, first contentful paint,
* and first input delay.
* See https://github.com/WICG/paint-timing
*/
registerPerformanceObserver_() {
// Chrome doesn't implement the buffered flag for PerformanceObserver.
// That means we need to read existing entries and maintain state
// as to whether we have reported a value yet, since in the future it may
// be reported twice.
// https://bugs.chromium.org/p/chromium/issues/detail?id=725567
let recordedFirstPaint = false;
let recordedFirstContentfulPaint = false;
let recordedFirstInputDelay = false;
const processEntry = entry => {
if (entry.name == 'first-paint' && !recordedFirstPaint) {
this.tickDelta('fp', entry.startTime + entry.duration);
recordedFirstPaint = true;
} else if (
entry.name == 'first-contentful-paint' &&
!recordedFirstContentfulPaint
) {
this.tickDelta('fcp', entry.startTime + entry.duration);
recordedFirstContentfulPaint = true;
} else if (
(entry.entryType === 'firstInput' ||
entry.entryType === 'first-input') &&
!recordedFirstInputDelay
) {
this.tickDelta('fid', entry.processingStart - entry.startTime);
recordedFirstInputDelay = true;
} else if (entry.entryType === 'layoutJank') {
this.aggregateJankScore_ += entry.fraction;
} else if (entry.entryType === 'layoutShift') {
this.aggregateShiftScore_ += entry.value;
} else if (entry.entryType === 'layout-shift') {
// Ignore layout shift that occurs within 500ms of user input, as it is
// likely in response to the user's action.
if (!entry.hadRecentInput) {
this.aggregateShiftScore_ += entry.value;
}
} else if (entry.entryType === 'largest-contentful-paint') {
if (entry.loadTime) {
this.largestContentfulPaintLoadTime_ = entry.loadTime;
}
if (entry.renderTime) {
this.largestContentfulPaintRenderTime_ = entry.renderTime;
}
}
};
const entryTypesToObserve = [];
if (this.win.PerformancePaintTiming) {
// Programmatically read once as currently PerformanceObserver does not
// report past entries as of Chrome 61.
// https://bugs.chromium.org/p/chromium/issues/detail?id=725567
this.win.performance.getEntriesByType('paint').forEach(processEntry);
entryTypesToObserve.push('paint');
}
if (this.supportsEventTimingAPIv76_) {
// Programmatically read once as currently PerformanceObserver does not
// report past entries as of Chrome 61.
// https://bugs.chromium.org/p/chromium/issues/detail?id=725567
this.win.performance.getEntriesByType('firstInput').forEach(processEntry);
entryTypesToObserve.push('firstInput');
}
if (this.supportsEventTimingAPIv77_) {
const firstInputObserver = this.createPerformanceObserver_(processEntry);
firstInputObserver.observe({type: 'first-input', buffered: true});
}
if (this.win.PerformanceLayoutJank) {
// Programmatically read once as currently PerformanceObserver does not
// report past entries as of Chrome 61.
// https://bugs.chromium.org/p/chromium/issues/detail?id=725567
this.win.performance.getEntriesByType('layoutJank').forEach(processEntry);
entryTypesToObserve.push('layoutJank');
}
if (this.supportsLayoutInstabilityAPIv76_) {
// Programmatically read once as currently PerformanceObserver does not
// report past entries as of Chrome 61.
// https://bugs.chromium.org/p/chromium/issues/detail?id=725567
this.win.performance
.getEntriesByType('layoutShift')
.forEach(processEntry);
entryTypesToObserve.push('layoutShift');
}
if (this.supportsLayoutInstabilityAPIv77_) {
const layoutInstabilityObserver = this.createPerformanceObserver_(
processEntry
);
layoutInstabilityObserver.observe({type: 'layout-shift', buffered: true});
}
if (this.supportsLargestContentfulPaint_) {
const lcpObserver = this.createPerformanceObserver_(processEntry);
lcpObserver.observe({type: 'largest-contentful-paint', buffered: true});
}
if (entryTypesToObserve.length === 0) {
return;
}
const observer = this.createPerformanceObserver_(processEntry);
// Wrap observer.observe() in a try statement for testing, because
// Webkit throws an error if the entry types to observe are not natively
// supported.
try {
observer.observe({entryTypes: entryTypesToObserve});
} catch (err) {
dev() /*OK*/
.warn(err);
}
}
/**
* @param {function(!PerformanceEntry)} processEntry
* @return {!PerformanceObserver}
* @private
*/
createPerformanceObserver_(processEntry) {
return new this.win.PerformanceObserver(list => {
list.getEntries().forEach(processEntry);
this.flush();
});
}
/**
* Reports the first input delay value calculated by a polyfill, if present.
* @see https://github.com/GoogleChromeLabs/first-input-delay
*/
registerFirstInputDelayPolyfillListener_() {
if (!this.win.perfMetrics || !this.win.perfMetrics.onFirstInputDelay) {
return;
}
this.win.perfMetrics.onFirstInputDelay(delay => {
this.tickDelta('fid-polyfill', delay);
this.flush();
});
}
/**
* When the visibility state of the document changes to hidden,
* send the layout jank score.
* @private
*/
onVisibilityChange_() {
if (this.win.document.visibilityState === 'hidden') {
if (this.win.PerformanceLayoutJank) {
this.tickLayoutJankScore_();
}
if (
this.supportsLayoutInstabilityAPIv76_ ||
this.supportsLayoutInstabilityAPIv77_
) {
this.tickLayoutShiftScore_();
}
if (this.supportsLargestContentfulPaint_) {
this.tickLargestContentfulPaint_();
}
}
}
/**
* When the viewer visibility state of the document changes to inactive,
* send the layout jank score.
* @private
*/
onAmpDocVisibilityChange_() {
if (this.ampdoc_.getVisibilityState() === VisibilityState.INACTIVE) {
if (this.win.PerformanceLayoutJank) {
this.tickLayoutJankScore_();
}
if (
this.supportsLayoutInstabilityAPIv76_ ||
this.supportsLayoutInstabilityAPIv77_
) {
this.tickLayoutShiftScore_();
}
if (this.supportsLargestContentfulPaint_) {
this.tickLargestContentfulPaint_();
}
}
}
/**
* Tick the layout jank score metric.
*
* A value of the metric is recorded in under two names, `lj` and `lj-2`,
* for the first two times the page transitions into a hidden lifecycle state
* (when the page is navigated a way from, the tab is backgrounded for
* another tab, or the user backgrounds the browser application).
*
* Since we can't reliably detect when a page session finally ends,
* recording the value for these first two events should provide a fair
* amount of visibility into this metric.
*/
tickLayoutJankScore_() {
if (this.jankScoresTicked_ === 0) {
this.tickDelta('lj', this.aggregateJankScore_);
this.flush();
this.jankScoresTicked_ = 1;
} else if (this.jankScoresTicked_ === 1) {
this.tickDelta('lj-2', this.aggregateJankScore_);
this.flush();
this.jankScoresTicked_ = 2;
// No more work to do, so clean up event listeners.
this.win.removeEventListener(
VISIBILITY_CHANGE_EVENT,
this.boundOnVisibilityChange_,
{capture: true}
);
}
}
/**
* Tick the layout shift score metric.
*
* A value of the metric is recorded in under two names, `cls` and `cls-2`,
* for the first two times the page transitions into a hidden lifecycle state
* (when the page is navigated a way from, the tab is backgrounded for
* another tab, or the user backgrounds the browser application).
*
* Since we can't reliably detect when a page session finally ends,
* recording the value for these first two events should provide a fair
* amount of visibility into this metric.
*/
tickLayoutShiftScore_() {
if (this.shiftScoresTicked_ === 0) {
this.tickDelta('cls', this.aggregateShiftScore_);
this.flush();
this.shiftScoresTicked_ = 1;
} else if (this.shiftScoresTicked_ === 1) {
this.tickDelta('cls-2', this.aggregateShiftScore_);
this.flush();
this.shiftScoresTicked_ = 2;
// No more work to do, so clean up event listeners.
this.win.removeEventListener(
VISIBILITY_CHANGE_EVENT,
this.boundOnVisibilityChange_,
{capture: true}
);
}
}
/**
* Tick fp time based on Chrome's legacy paint timing API when
* appropriate.
* `registerPaintTimingObserver_` calls the standards based API and this
* method does nothing if it is available.
*/
tickLegacyFirstPaintTime_() {
// Detect deprecated first pain time API
// https://bugs.chromium.org/p/chromium/issues/detail?id=621512
// We'll use this until something better is available.
if (
!this.win.PerformancePaintTiming &&
this.win.chrome &&
typeof this.win.chrome.loadTimes == 'function'
) {
const fpTime =
this.win.chrome.loadTimes()['firstPaintTime'] * 1000 -
this.win.performance.timing.navigationStart;
if (fpTime <= 1) {
// Throw away bad data generated from an apparent Chrome bug
// that is fixed in later Chrome versions.
return;
}
this.tickDelta('fp', fpTime);
}
}
/**
* Tick the largest contentful paint metrics.
*/
tickLargestContentfulPaint_() {
if (this.largestContentfulPaintLoadTime_ !== null) {
this.tickDelta('lcpl', this.largestContentfulPaintLoadTime_);
}
if (this.largestContentfulPaintRenderTime_ !== null) {
this.tickDelta('lcpr', this.largestContentfulPaintRenderTime_);
}
this.flush();
}
/**
* Measure the delay the user perceives of how long it takes
* to load the initial viewport.
* @private
*/
measureUserPerceivedVisualCompletenessTime_() {
const didStartInPrerender = !this.ampdoc_.hasBeenVisible();
let docVisibleTime = didStartInPrerender ? -1 : this.initTime_;
// This will only be relevant if the ampdoc is in prerender mode.
// (hasn't been visible yet, ever at this point)
this.ampdoc_.whenFirstVisible().then(() => {
docVisibleTime = this.win.Date.now();
// Mark this first visible instance in the browser timeline.
this.mark('visible');
});
this.whenViewportLayoutComplete_().then(() => {
if (didStartInPrerender) {
const userPerceivedVisualCompletenesssTime =
docVisibleTime > -1
? this.win.Date.now() - docVisibleTime
: // Prerender was complete before visibility.
0;
this.ampdoc_.whenFirstVisible().then(() => {
// We only tick this if the page eventually becomes visible,
// since otherwise we heavily skew the metric towards the
// 0 case, since pre-renders that are never used are highly
// likely to fully load before they are never used :)
this.tickDelta('pc', userPerceivedVisualCompletenesssTime);
});
this.prerenderComplete_(userPerceivedVisualCompletenesssTime);
// Mark this instance in the browser timeline.
this.mark('pc');
} else {
// If it didnt start in prerender, no need to calculate anything
// and we just need to tick `pc`. (it will give us the relative
// time since the viewer initialized the timer)
this.tick('pc');
// We don't have the actual csi timer's clock start time,
// so we just have to use `docVisibleTime`.
this.prerenderComplete_(this.win.Date.now() - docVisibleTime);
}
this.flush();
});
}
/**
* Returns a promise that is resolved when resources in viewport
* have been finished being laid out.
* @return {!Promise}
* @private
*/
whenViewportLayoutComplete_() {
const {documentElement} = this.win.document;
const size = Services.viewportForDoc(documentElement).getSize();
const rect = layoutRectLtwh(0, 0, size.width, size.height);
return this.resources_.whenFirstPass().then(() => {
return whenContentIniLoad(
documentElement,
this.win,
rect,
/* isInPrerender */ true
);
});
}
/**
* Ticks a timing event.
*
* @param {string} label The variable name as it will be reported.
* See TICKEVENTS.md for available metrics, and edit this file
* when adding a new metric.
* @param {number=} opt_delta The delta. Call tickDelta instead of setting
* this directly.
*/
tick(label, opt_delta) {
const data = dict({'label': label});
let storedVal;
// Absolute value case (not delta).
if (opt_delta == undefined) {
// Marking only makes sense for non-deltas.
this.mark(label);
const now = this.win.Date.now();
data['value'] = now;
storedVal = now - this.initTime_;
} else {
data['delta'] = storedVal = Math.max(opt_delta, 0);
}
if (this.isMessagingReady_ && this.isPerformanceTrackingOn_) {
this.viewer_.sendMessage('tick', data);
} else {
this.queueTick_(data);
}
switch (label) {
case 'fcp':
this.fcpDeferred_.resolve(storedVal);
break;
case 'pc':
this.fvrDeferred_.resolve(storedVal);
break;
case 'mbv':
this.mbvDeferred_.resolve(storedVal);
break;
}
}
/**
* Add browser performance timeline entries for simple ticks.
* These are for example exposed in WPT.
* See https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark
* @param {string} label
*/
mark(label) {
if (
this.win.performance &&
this.win.performance.mark &&
arguments.length == 1
) {
this.win.performance.mark(label);
}
}
/**
* Tick a very specific value for the label. Use this method if you
* measure the time it took to do something yourself.
* @param {string} label The variable name as it will be reported.
* @param {number} value The value in milliseconds that should be ticked.
*/
tickDelta(label, value) {
this.tick(label, value);
}
/**
* Tick time delta since the document has become visible.
* @param {string} label The variable name as it will be reported.
*/
tickSinceVisible(label) {
const now = this.win.Date.now();
const visibleTime = this.ampdoc_ ? this.ampdoc_.getFirstVisibleTime() : 0;
const v = visibleTime ? Math.max(now - visibleTime, 0) : 0;
this.tickDelta(label, v);
}
/**
* Ask the viewer to flush the ticks
*/
flush() {
if (this.isMessagingReady_ && this.isPerformanceTrackingOn_) {
this.viewer_.sendMessage(
'sendCsi',
dict({
'ampexp': this.ampexp_,
}),
/* cancelUnsent */ true
);
}
}
/**
* Flush with a rate limit of 10 per second.
*/
throttledFlush() {
if (!this.throttledFlush_) {
/** @private {function()} */
this.throttledFlush_ = throttle(this.win, this.flush.bind(this), 100);
}
this.throttledFlush_();
}
/**
* @param {string} experimentId
*/
addEnabledExperiment(experimentId) {
this.enabledExperiments_[experimentId] = true;
this.ampexp_ = Object.keys(this.enabledExperiments_).join(',');
}
/**
* Queues the events to be flushed when tick function is set.
*
* @param {TickEventDef} data Tick data to be queued.
* @private
*/
queueTick_(data) {
// Start dropping the head of the queue if we've reached the limit
// so that we don't take up too much memory in the runtime.
if (this.events_.length >= QUEUE_LIMIT) {
this.events_.shift();
}
this.events_.push(data);
}
/**
* Forwards all queued ticks to the viewer tick method.
* @private
*/
flushQueuedTicks_() {
if (!this.viewer_) {
return;
}
if (!this.isPerformanceTrackingOn_) {
// drop all queued ticks to not leak
this.events_.length = 0;
return;
}
this.events_.forEach(tickEvent => {
this.viewer_.sendMessage('tick', tickEvent);
});
this.events_.length = 0;
}
/**
* @private
* @param {number} value
*/
prerenderComplete_(value) {
if (this.viewer_) {
this.viewer_.sendMessage(
'prerenderComplete',
dict({'value': value}),
/* cancelUnsent */ true
);
}
}
/**
* Identifies if the viewer is able to track performance. If the document is
* not embedded, there is no messaging channel, so no performance tracking is
* needed since there is nobody to forward the events.
* @return {boolean}
*/
isPerformanceTrackingOn() {
return this.isPerformanceTrackingOn_;
}
/**
* @return {!Promise<number>}
*/
getFirstContentfulPaint() {
return this.fcpDeferred_.promise;
}
/**
* @return {!Promise<number>}
*/
getMakeBodyVisible() {
return this.mbvDeferred_.promise;
}
/**
* @return {!Promise<number>}
*/
getFirstViewportReady() {
return this.fvrDeferred_.promise;
}
}
/**
* @param {!Window} window
*/
export function installPerformanceService(window) {
registerServiceBuilder(window, 'performance', Performance);
}
/**
* @param {!Window} window
* @return {!Performance}
*/
export function performanceFor(window) {
return getService(window, 'performance');
}