-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
page-dependency-graph.js
302 lines (257 loc) · 9.66 KB
/
page-dependency-graph.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
/**
* @license Copyright 2017 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 ComputedArtifact = require('./computed-artifact');
const NetworkNode = require('./dependency-graph/network-node');
const CPUNode = require('./dependency-graph/cpu-node');
const GraphEstimator = require('./dependency-graph/estimator/estimator');
const TracingProcessor = require('../../lib/traces/tracing-processor');
// tasks shorter than 10 ms are unlikely have a significant impact
const MINIMUM_TASK_DURATION = 10000;
// video files tend to be enormous and throw off all graph traversals
const IGNORED_MIME_TYPES_REGEX = /^video/;
class PageDependencyGraphArtifact extends ComputedArtifact {
get name() {
return 'PageDependencyGraph';
}
get requiredNumberOfArtifacts() {
return 2;
}
/**
* @param {!WebInspector.NetworkRequest} record
* @return {!Array<string>}
*/
static getNetworkInitiators(record) {
if (!record._initiator) return [];
if (record._initiator.url) return [record._initiator.url];
if (record._initiator.type === 'script') {
const frames = record._initiator.stack.callFrames;
return Array.from(new Set(frames.map(frame => frame.url))).filter(Boolean);
}
return [];
}
/**
* @param {!Array<!WebInspector.NetworkRequest>} networkRecords
* @return {!NetworkNodeOutput}
*/
static getNetworkNodes(networkRecords) {
const nodes = [];
const idToNodeMap = new Map();
const urlToNodeMap = new Map();
networkRecords.forEach(record => {
if (IGNORED_MIME_TYPES_REGEX.test(record.mimeType)) return;
const node = new NetworkNode(record);
nodes.push(node);
idToNodeMap.set(record.requestId, node);
if (urlToNodeMap.has(record.url)) {
const list = urlToNodeMap.get(record.url);
list.push(node);
} else {
urlToNodeMap.set(record.url, [node]);
}
});
return {nodes, idToNodeMap, urlToNodeMap};
}
/**
* @param {!TraceOfTabArtifact} traceOfTab
* @return {!Array<!CPUNode>}
*/
static getCPUNodes(traceOfTab) {
const nodes = [];
let i = 0;
while (i < traceOfTab.mainThreadEvents.length) {
const evt = traceOfTab.mainThreadEvents[i];
// Skip all trace events that aren't schedulable tasks with sizable duration
if (
evt.name !== TracingProcessor.SCHEDULABLE_TASK_TITLE ||
!evt.dur ||
evt.dur < MINIMUM_TASK_DURATION
) {
i++;
continue;
}
// Capture all events that occurred within the task
const children = [];
i++; // Start examining events after this one
for (
const endTime = evt.ts + evt.dur;
i < traceOfTab.mainThreadEvents.length && traceOfTab.mainThreadEvents[i].ts < endTime;
i++
) {
children.push(traceOfTab.mainThreadEvents[i]);
}
nodes.push(new CPUNode(evt, children));
}
return nodes;
}
/**
* @param {!Node} rootNode
* @param {!NetworkNodeOutput} networkNodeOutput
*/
static linkNetworkNodes(rootNode, networkNodeOutput) {
networkNodeOutput.nodes.forEach(node => {
const initiators = PageDependencyGraphArtifact.getNetworkInitiators(node.record);
if (initiators.length) {
initiators.forEach(initiator => {
const parentCandidates = networkNodeOutput.urlToNodeMap.get(initiator) || [rootNode];
// Only add the initiator relationship if the initiator is unambiguous
const parent = parentCandidates.length === 1 ? parentCandidates[0] : rootNode;
parent.addDependent(node);
});
} else if (node !== rootNode) {
rootNode.addDependent(node);
}
});
}
/**
* @param {!Node} rootNode
* @param {!NetworkNodeOutput} networkNodeOutput
* @param {!Array<!CPUNode>} cpuNodes
* @param {!TraceOfTabArtifact} traceOfTab
*/
static linkCPUNodes(rootNode, networkNodeOutput, cpuNodes) {
function addDependentNetworkRequest(cpuNode, reqId) {
const networkNode = networkNodeOutput.idToNodeMap.get(reqId);
if (!networkNode || networkNode.resourceType !== 'xhr') return;
networkNode.addDependency(cpuNode);
}
function addDependencyOnUrl(cpuNode, url) {
const candidates = networkNodeOutput.urlToNodeMap.get(url) || [];
let minCandidate = null;
let minDistance = Infinity;
// Find the closest request that finished before this CPU task started
candidates.forEach(candidate => {
const distance = cpuNode.startTime - candidate.endTime;
if (distance > 0 && distance < minDistance) {
minCandidate = candidate;
minDistance = distance;
}
});
if (!minCandidate) return;
cpuNode.addDependency(minCandidate);
}
const timers = new Map();
for (const node of cpuNodes) {
for (const evt of node.children) {
if (!evt.args.data) continue;
const url = evt.args.data.url;
const stackTraceUrls = (evt.args.data.stackTrace || []).map(l => l.url).filter(Boolean);
switch (evt.name) {
case 'TimerInstall':
timers.set(evt.args.data.timerId, node);
stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
break;
case 'TimerFire': {
const installer = timers.get(evt.args.data.timerId);
if (!installer) break;
installer.addDependent(node);
break;
}
case 'InvalidateLayout':
case 'ScheduleStyleRecalculation':
stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
break;
case 'EvaluateScript':
addDependencyOnUrl(node, url);
stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
break;
case 'XHRReadyStateChange':
// Only create the dependency if the request was completed
if (evt.args.data.readyState !== 4) break;
addDependencyOnUrl(node, url);
stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
break;
case 'FunctionCall':
case 'v8.compile':
addDependencyOnUrl(node, url);
break;
case 'ParseAuthorStyleSheet':
addDependencyOnUrl(node, evt.args.data.styleSheetUrl);
break;
case 'ResourceSendRequest':
addDependentNetworkRequest(node, evt.args.data.requestId, evt);
stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
break;
}
}
if (node.getNumberOfDependencies() === 0) {
node.addDependency(rootNode);
}
}
}
/**
* @param {!TraceOfTabArtifact} traceOfTab
* @param {!Array<!WebInspector.NetworkRequest>} networkRecords
* @return {!Node}
*/
static createGraph(traceOfTab, networkRecords) {
const networkNodeOutput = this.getNetworkNodes(networkRecords);
const cpuNodes = this.getCPUNodes(traceOfTab);
const rootRequest = networkRecords.reduce((min, r) => (min.startTime < r.startTime ? min : r));
const rootNode = networkNodeOutput.idToNodeMap.get(rootRequest.requestId);
this.linkNetworkNodes(rootNode, networkNodeOutput, networkRecords);
this.linkCPUNodes(rootNode, networkNodeOutput, cpuNodes, traceOfTab);
return rootNode;
}
/**
* @param {!Node} rootNode
* @return {}
*/
static estimateGraph(rootNode) {
return new GraphEstimator(rootNode).estimateWithDetails();
}
/**
*
* @param {!Node} rootNode
*/
static printGraph(rootNode, widthInCharacters = 100) {
function padRight(str, target, padChar = ' ') {
while (str.length < target) {
str += padChar;
}
return str;
}
const nodes = [];
rootNode.traverse(node => nodes.push(node));
nodes.sort((a, b) => a.startTime - b.startTime);
const min = nodes[0].startTime;
const max = nodes.reduce((max, node) => Math.max(max, node.endTime), 0);
const totalTime = max - min;
const timePerCharacter = totalTime / widthInCharacters;
nodes.forEach(node => {
const offset = Math.round((node.startTime - min) / timePerCharacter);
const length = Math.ceil((node.endTime - node.startTime) / timePerCharacter);
const bar = padRight('', offset) + padRight('', length, '=');
const displayName = node.record ? node.record._url : node.type;
// eslint-disable-next-line
console.log(padRight(bar, widthInCharacters), `| ${displayName.slice(0, 30)}`);
});
}
/**
* @param {!Trace} trace
* @param {!DevtoolsLog} devtoolsLog
* @param {!ComputedArtifacts} artifacts
* @return {!Promise<!Node>}
*/
compute_(trace, devtoolsLog, artifacts) {
const promises = [
artifacts.requestTraceOfTab(trace),
artifacts.requestNetworkRecords(devtoolsLog),
];
return Promise.all(promises).then(([traceOfTab, networkRecords]) => {
return PageDependencyGraphArtifact.createGraph(traceOfTab, networkRecords);
});
}
}
module.exports = PageDependencyGraphArtifact;
/**
* @typedef {{
* nodes: !Array<!NetworkNode>,
* idToNodeMap: !Map<string, !NetworkNode>,
* urlToNodeMap: !Map<string, !Array<!NetworkNode>
* }}
*/
PageDependencyGraphArtifact.NetworkNodeOutput; // eslint-disable-line no-unused-expressions