-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
critical-request-chains.js
307 lines (257 loc) · 9.41 KB
/
critical-request-chains.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
/**
* @license
* Copyright 2016 Google Inc. 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.
*/
'use strict';
const url = require('url');
const path = require('path');
const fs = require('fs');
const Formatter = require('./formatter');
const html = fs.readFileSync(path.join(__dirname, 'partials/critical-request-chains.html'), 'utf8');
class CriticalRequestChains extends Formatter {
/**
* gets the formatter for the CLI Printer and the HTML report.
*/
static getFormatter(type) {
switch (type) {
case 'pretty':
return function(info) {
if (info === null ||
typeof info === 'undefined') {
return '';
}
const longestChain = CriticalRequestChains._getLongestChainLength(info);
const longestDuration =
CriticalRequestChains._getLongestChainDuration(info).toFixed(2);
const longestTransferSize = CriticalRequestChains.formatTransferSize(
CriticalRequestChains._getLongestChainTransferSize(info));
const urlTree = CriticalRequestChains._createURLTreeOutput(info);
const output = ` - Longest request chain (shorter is better): ${longestChain}\n` +
` - Longest chain duration (shorter is better): ${longestDuration}ms\n` +
` - Longest chain transfer size (smaller is better): ${longestTransferSize}KB\n` +
' - Initial navigation\n' +
' ' + urlTree.replace(/\n/g, '\n ') + '\n';
return output;
};
case 'html':
// Returns a handlebars string to be used by the Report.
return html;
default:
throw new Error('Unknown formatter type');
}
}
static _traverse(tree, cb) {
function walk(node, depth, startTime, transferSize) {
const children = Object.keys(node);
if (children.length === 0) {
return;
}
if (!transferSize) {
transferSize = 0;
}
children.forEach(id => {
const child = node[id];
if (!startTime) {
startTime = child.request.startTime;
}
// Call the callback with the info for this child.
cb({
depth,
id,
node: child,
chainDuration: (child.request.endTime - startTime) * 1000,
chainTransferSize: (transferSize + child.request.transferSize)
});
// Carry on walking.
walk(child.children, depth + 1, startTime);
}, '');
}
walk(tree, 0);
}
static _getLongestChainLength(tree) {
let longestChain = 0;
this._traverse(tree, opts => {
const depth = opts.depth;
if (depth > longestChain) {
longestChain = depth;
}
});
// Always return the longest chain + 1 because the depth is zero indexed.
return (longestChain + 1);
}
static _getLongestChainDuration(tree) {
let longestChainDuration = 0;
this._traverse(tree, opts => {
const duration = opts.chainDuration;
if (duration > longestChainDuration) {
longestChainDuration = duration;
}
});
return longestChainDuration;
}
static _getLongestChainTransferSize(tree) {
let transferSize = 0;
this._traverse(tree, opts => {
const chainTransferSize = opts.chainTransferSize;
if (chainTransferSize > transferSize) {
transferSize = chainTransferSize;
}
});
return transferSize;
}
/**
* Converts the tree into an ASCII tree.
*/
static _createURLTreeOutput(tree) {
function write(opts) {
const node = opts.node;
const depth = opts.depth;
const treeMarkers = opts.treeMarkers;
let startTime = opts.startTime;
let transferSize = opts.transferSize;
return Object.keys(node).reduce((output, id, currentIndex, arr) => {
// Test if this node has children, and if it's the last child.
const hasChildren = (Object.keys(node[id].children).length > 0);
const isLastChild = (currentIndex === arr.length - 1);
// If the parent is the last child then don't drop the vertical bar.
const ancestorTreeMarker = treeMarkers.reduce((markers, marker) => {
return markers + (marker ? '┃ ' : ' ');
}, '');
// Copy the tree markers so that we don't change by reference.
const newTreeMakers = treeMarkers.slice(0);
// Add on the new entry.
newTreeMakers.push(!isLastChild);
// Create the appropriate tree marker based on the depth of this
// node as well as whether or not it has children and is itself the last child.
const treeMarker = ancestorTreeMarker +
(isLastChild ? '┗━' : '┣━') +
(hasChildren ? '┳' : '━');
const parsedURL = CriticalRequestChains.parseURL(node[id].request.url);
if (!startTime) {
startTime = node[id].request.startTime;
}
const duration = ((node[id].request.endTime - startTime) * 1000).toFixed(2);
const chainTransferSize = transferSize + node[id].request.transferSize;
const formattedTransferSize = CriticalRequestChains.formatTransferSize(chainTransferSize);
// Return the previous output plus this new node, and recursively write its children.
return output + `${treeMarker} ${parsedURL.file} (${parsedURL.hostname})` +
// If this node has children, write them out. Othewise write the chain time.
(hasChildren ? '' : ` - ${duration}ms, ${formattedTransferSize}KB`) + '\n' +
write({
node: node[id].children,
depth: depth + 1,
treeMarkers: newTreeMakers,
startTime,
transferSize: chainTransferSize
});
}, '');
}
return write({
node: tree,
depth: 0,
treeMarkers: [],
startTime: 0,
transferSize: 0
});
}
static formatTime(time) {
return time.toFixed(2);
}
static formatTransferSize(size) {
return (size / 1024).toFixed(2);
}
static parseURL(resourceURL, opts) {
const MAX_FILENAME_LENGTH = 64;
const parsedResourceURL = url.parse(resourceURL);
const hostname = parsedResourceURL.hostname;
let file = parsedResourceURL.path
// Remove any query strings.
.replace(/\?.*/, '')
// Grab the last two parts of the path.
.split('/').slice(-2).join('/');
if (file.length > MAX_FILENAME_LENGTH) {
file = file.slice(0, MAX_FILENAME_LENGTH) + '...';
}
const parsedURL = {
file,
hostname
};
// If we get passed the opts parameter, this is Handlebars, so we
// need to return the object back via the opts.fn so it becomes the context.
if (opts) {
return opts.fn(parsedURL);
}
return parsedURL;
}
static getHelpers() {
return {
longestChain(info) {
return CriticalRequestChains._getLongestChainLength(info);
},
longestDuration(info) {
return CriticalRequestChains._getLongestChainDuration(info);
},
longestChainTransferSize(info) {
return CriticalRequestChains._getLongestChainTransferSize(info);
},
chainDuration(startTime, endTime) {
return ((endTime - startTime) * 1000).toFixed(2);
},
formatTransferSize: CriticalRequestChains.formatTransferSize,
parseURL: CriticalRequestChains.parseURL,
formatTime: CriticalRequestChains.formatTime,
/**
* Helper function for Handlebars that creates the context for each node
* based on its parent. Calculates if this node is the last child, whether
* it has any children itself and what the tree looks like all the way back
* up to the root, so the tree markers can be drawn correctly.
*/
createContextFor(parent, id, treeMarkers, parentIsLastChild, startTime, transferSize, opts) {
const node = parent[id];
const siblings = Object.keys(parent);
const isLastChild = siblings.indexOf(id) === (siblings.length - 1);
const hasChildren = Object.keys(node.children).length > 0;
// Copy the tree markers so that we don't change by reference.
const newTreeMarkers = Array.isArray(treeMarkers) ? treeMarkers.slice(0) : [];
// Add on the new entry.
if (typeof parentIsLastChild !== 'undefined') {
newTreeMarkers.push(!parentIsLastChild);
}
return opts.fn({
node,
isLastChild,
hasChildren,
startTime,
transferSize: (transferSize + node.request.transferSize),
treeMarkers: newTreeMarkers
});
},
createTreeRenderContext(tree, opts) {
const transferSize = 0;
let startTime = 0;
const rootNodes = Object.keys(tree);
if (rootNodes.length > 0) {
startTime = tree[rootNodes[0]].request.startTime;
}
return opts.fn({
tree,
startTime,
transferSize
});
}
};
}
}
module.exports = CriticalRequestChains;