forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperformance.js
332 lines (286 loc) · 9.34 KB
/
performance.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
/**
* 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 {documentInfoFor} from './document-info';
import {onDocumentReady} from './document-ready';
import {getService} from './service';
import {loadPromise} from './event-helper';
import {resourcesFor} from './resources';
import {timer} from './timer';
import {viewerFor} from './viewer';
/**
* 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;
/**
* Added to relative relative timings so that they are never 0 which the
* underlying library considers a non-value.
*/
export const ENSURE_NON_ZERO = new Date().getTime();
/**
* @typedef {{
* label: string,
* opt_from: (string|null|undefined),
* opt_value: (number|undefined)
* }}
*/
class 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;
/** @const @private {funtion(string,?string=,number=)|undefined} */
this.tick_ = undefined;
/** @const @private {funtion()|undefined} */
this.flush_ = undefined;
/** @const @private {!Array<TickEventDef>} */
this.events_ = [];
/** @private {?Viewer} */
this.viewer_ = null;
/** @private {?Resources} */
this.resources = null;
/** @private @const {!Promise} */
this.whenReadyToRetrieveResourcesPromise_ = new Promise(resolve => {
onDocumentReady(this.win.document, () => {
// We need to add a delay, since this can execute earlier
// than the onReady callback registered inside of `Resources`.
// Should definitely think of making `getResourcesInViewport` async.
timer.delay(resolve);
});
});
// Tick window.onload event.
loadPromise(win).then(() => {
this.tick('ol');
});
}
/**
* Listens to viewer and resource events.
*/
coreServicesAvailable() {
this.viewer_ = viewerFor(this.win);
this.resources_ = resourcesFor(this.win);
this.viewer_.onVisibilityChanged(this.flush.bind(this));
this.measureUserPerceivedVisualCompletenessTime_();
this.setDocumentInfoParams_();
// forward all queued ticks to the viewer.
this.flushQueuedTicks_();
// We need to call flush right away in case the viewer is available
// later than the amp codebase had invoked the performance services'
// `flush` method to forward ticks.
this.flush();
}
/**
* Measure the delay the user perceives of how long it takes
* to load the initial viewport.
* @private
*/
measureUserPerceivedVisualCompletenessTime_() {
const didStartInPrerender = !this.viewer_.hasBeenVisible();
let docVisibleTime = didStartInPrerender ? -1 : timer.now();
// This is only relevant if the viewer is in prerender mode.
// (hasn't been visible yet, ever at this point)
if (didStartInPrerender) {
this.viewer_.whenFirstVisible().then(() => {
docVisibleTime = timer.now();
});
}
this.whenViewportLayoutComplete_().then(() => {
if (didStartInPrerender) {
const userPerceivedVisualCompletenesssTime = docVisibleTime > -1
? (timer.now() - docVisibleTime)
: 1 /* MS (magic number for prerender was complete
by the time the user opened the page) */;
this.tickDelta('pc', userPerceivedVisualCompletenesssTime);
} 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');
}
});
}
/**
* Returns a promise that is resolved when resources in viewport
* have been finished being laid out.
* @return {!Promise}
* @private
*/
whenViewportLayoutComplete_() {
return this.whenReadyToRetrieveResources_().then(() => {
return Promise.all(this.resources_.getResourcesInViewport().map(r => {
// We're ok with the layout failing and still reporting.
return r.loaded().catch(function() {});
}));
});
}
/**
* Returns a promise that is resolved when the document is ready and
* after a microtask delay.
* @return {!Promise}
*/
whenReadyToRetrieveResources_() {
return this.whenReadyToRetrieveResourcesPromise_;
}
/**
* Forward an object to be appended as search params to the external
* intstrumentation library.
* @param {!JSONObject} params
* @private
*/
setFlushParams_(params) {
this.viewer_.setFlushParams(params);
}
/**
* Ticks a timing event.
*
* @param {string} label The variable name as it will be reported.
* @param {?string=} opt_from The label of a previous tick to use as a
* relative start for this tick.
* @param {number=} opt_value The time to record the tick at. Optional, if
* not provided, use the current time. You probably want to use
* `tickDelta` instead.
*/
tick(label, opt_from, opt_value) {
opt_from = opt_from == undefined ? null : opt_from;
opt_value = opt_value == undefined ? timer.now() : opt_value;
if (this.viewer_ && this.viewer_.isPerformanceTrackingOn()) {
this.viewer_.tick({
'label': label,
'from': opt_from,
'value': opt_value,
});
} else {
this.queueTick_(label, opt_from, opt_value);
}
}
/**
* 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) {
// ENSURE_NON_ZERO Is added instead of non-zero, because the underlying
// library doesn't like 0 values.
this.tick('_' + label, undefined, ENSURE_NON_ZERO);
this.tick(label, '_' + label, Math.round(value + ENSURE_NON_ZERO));
}
/**
* Calls the "flushTicks" function on the viewer.
*/
flush() {
if (this.viewer_ && this.viewer_.isPerformanceTrackingOn()) {
this.viewer_.flushTicks();
}
}
/**
* Queues the events to be flushed when tick function is set.
*
* @param {string} label The variable name as it will be reported.
* @param {?string=} opt_from The label of a previous tick to use as a
* relative start for this tick.
* @param {number=} opt_value The time to record the tick at. Optional, if
* not provided, use the current time.
* @private
*/
queueTick_(label, opt_from, opt_value) {
// 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({
'label': label,
'from': opt_from,
'value': opt_value,
});
}
/**
* Forwards all queued ticks to the viewer tick method.
* @private
*/
flushQueuedTicks_() {
if (!this.viewer_) {
return;
}
if (!this.viewer_.isPerformanceTrackingOn()) {
// drop all queued ticks to not leak
this.events_.length = 0;
return;
}
this.events_.forEach(tickEvent => {
this.viewer_.tick(tickEvent);
});
this.events_.length = 0;
}
/**
* Calls "setFlushParams_" with relevant document information.
* @return {!Promise}
* @private
*/
setDocumentInfoParams_() {
return this.whenViewportLayoutComplete_().then(() => {
const params = Object.create(null);
const sourceUrl = documentInfoFor(this.win).sourceUrl
.replace(/#.*/, '');
params['sourceUrl'] = sourceUrl;
this.resources_.get().forEach(r => {
const el = r.element;
const name = el.tagName.toLowerCase();
incOrDef(params, name);
if (name == 'amp-ad') {
incOrDef(params, `ad-${el.getAttribute('type')}`);
}
});
// this should be guaranteed to be at the very least on the last
// visibility flush.
this.setFlushParams_(params);
});
}
}
/**
* @param {!Window} window
* @return {!Performance}
*/
export function performanceFor(window) {
return getService(window, 'performance', () => {
return new Performance(window);
});
};