Skip to content

Commit

Permalink
new_audit: add preconnect audit (avoid costly origin roundtrips) (#4362)
Browse files Browse the repository at this point in the history
  • Loading branch information
wardpeet authored and paulirish committed Apr 26, 2018
1 parent 55a9a69 commit 1176a63
Show file tree
Hide file tree
Showing 14 changed files with 434 additions and 14 deletions.
3 changes: 3 additions & 0 deletions lighthouse-cli/test/fixtures/perf/preload_tester.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@
/* eslint-disable */

document.write('<script src="level-2.js?delay=500"></script>')

// load another origin
fetch('http://localhost:10503/preload.html');
8 changes: 8 additions & 0 deletions lighthouse-cli/test/smokehouse/perf/expectations.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ module.exports = [
},
},
},
'uses-rel-preconnect': {
score: '<1',
details: {
items: {
length: 1,
},
},
},
},
},
{
Expand Down
2 changes: 1 addition & 1 deletion lighthouse-core/audits/audit.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class Audit {

/**
* @param {Array<LH.Audit.Heading>} headings
* @param {Array<Object<string, string>>} results
* @param {Array<Object<string, string|number>>} results
* @param {LH.Audit.DetailsRendererDetailsSummary} summary
* @return {LH.Audit.DetailsRendererDetailsJSON}
*/
Expand Down
152 changes: 152 additions & 0 deletions lighthouse-core/audits/uses-rel-preconnect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* @license Copyright 2018 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 Audit = require('./audit');
const Util = require('../report/html/renderer/util');
const UnusedBytes = require('./byte-efficiency/byte-efficiency-audit');
// Preconnect establishes a "clean" socket. Chrome's socket manager will keep an unused socket
// around for 10s. Meaning, the time delta between processing preconnect a request should be <10s,
// otherwise it's wasted. We add a 5s margin so we are sure to capture all key requests.
// @see https://github.com/GoogleChrome/lighthouse/issues/3106#issuecomment-333653747
const PRECONNECT_SOCKET_MAX_IDLE = 15;

class UsesRelPreconnectAudit extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
name: 'uses-rel-preconnect',
description: 'Avoid multiple, costly round trips to any origin',
informative: true,
helpText:
'Consider adding preconnect or dns-prefetch resource hints to establish early ' +
`connections to important third-party origins. [Learn more](https://developers.google.com/web/fundamentals/performance/resource-prioritization#preconnect).`,
requiredArtifacts: ['devtoolsLogs'],
scoreDisplayMode: Audit.SCORING_MODES.NUMERIC,
};
}

/**
* Check if record has valid timing
* @param {!LH.WebInspector.NetworkRequest} record
* @return {!boolean}
*/
static hasValidTiming(record) {
return record._timing && record._timing.connectEnd > 0 && record._timing.connectStart > 0;
}

/**
* Check is the connection is already open
* @param {!LH.WebInspector.NetworkRequest} record
* @return {!boolean}
*/
static hasAlreadyConnectedToOrigin(record) {
return (
record._timing.dnsEnd - record._timing.dnsStart === 0 &&
record._timing.connectEnd - record._timing.connectStart === 0
);
}

/**
* Check is the connection has started before the socket idle time
* @param {!LH.WebInspector.NetworkRequest} record
* @param {!LH.WebInspector.NetworkRequest} mainResource
* @return {!boolean}
*/
static socketStartTimeIsBelowThreshold(record, mainResource) {
return Math.max(0, record.startTime - mainResource.endTime) < PRECONNECT_SOCKET_MAX_IDLE;
}

/**
* @param {LH.Artifacts} artifacts
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts) {
const devtoolsLogs = artifacts.devtoolsLogs[UsesRelPreconnectAudit.DEFAULT_PASS];
let maxWasted = 0;

const [networkRecords, mainResource] = await Promise.all([
artifacts.requestNetworkRecords(devtoolsLogs),
artifacts.requestMainResource(devtoolsLogs),
]);

/** @type {Map<string, LH.WebInspector.NetworkRequest[]>} */
const origins = new Map();
networkRecords
.forEach(record => {
if (
// filter out all resources where timing info was invalid
!UsesRelPreconnectAudit.hasValidTiming(record) ||
// filter out all resources that are loaded by the document
record.initiatorRequest() === mainResource ||
// filter out urls that do not have an origin (data, ...)
!record.parsedURL || !record.parsedURL.securityOrigin() ||
// filter out all resources that have the same origin
mainResource.parsedURL.securityOrigin() === record.parsedURL.securityOrigin() ||
// filter out all resources where origins are already resolved
UsesRelPreconnectAudit.hasAlreadyConnectedToOrigin(record) ||
// make sure the requests are below the PRECONNECT_SOCKET_MAX_IDLE (15s) mark
!UsesRelPreconnectAudit.socketStartTimeIsBelowThreshold(record, mainResource)
) {
return;
}

const securityOrigin = record.parsedURL.securityOrigin();
const records = origins.get(securityOrigin) || [];
records.push(record);
origins.set(securityOrigin, records);
});

/** @type {Array<{url: string, type: 'ms', wastedMs: number}>}*/
let results = [];
origins.forEach(records => {
// Sometimes requests are done simultaneous and the connection has not been made
// chrome will try to connect for each network record, we get the first record
const firstRecordOfOrigin = records.reduce((firstRecord, record) => {
return (record.startTime < firstRecord.startTime) ? record: firstRecord;
});

const connectionTime =
firstRecordOfOrigin._timing.connectEnd - firstRecordOfOrigin._timing.dnsStart;
const timeBetweenMainResourceAndDnsStart =
firstRecordOfOrigin.startTime * 1000 -
mainResource.endTime * 1000 +
firstRecordOfOrigin._timing.dnsStart;
const wastedMs = Math.min(connectionTime, timeBetweenMainResourceAndDnsStart);
maxWasted = Math.max(wastedMs, maxWasted);
results.push({
url: firstRecordOfOrigin.parsedURL.securityOrigin(),
type: 'ms',
wastedMs: wastedMs,
});
});

results = results
.sort((a, b) => b.wastedMs - a.wastedMs);

const headings = [
{key: 'url', itemType: 'url', text: 'Origin'},
{key: 'wastedMs', itemType: 'ms', text: 'Potential Savings'},
];
const summary = {wastedMs: maxWasted};
const details = Audit.makeTableDetails(headings, results, summary);

return {
score: UnusedBytes.scoreForWastedMs(maxWasted),
rawValue: maxWasted,
displayValue: Util.formatMilliseconds(maxWasted),
extendedInfo: {
value: results,
},
details,
};
}
}

module.exports = UsesRelPreconnectAudit;
2 changes: 2 additions & 0 deletions lighthouse-core/config/default-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ module.exports = {
'mainthread-work-breakdown',
'bootup-time',
'uses-rel-preload',
'uses-rel-preconnect',
'font-display',
'network-requests',
'metrics',
Expand Down Expand Up @@ -278,6 +279,7 @@ module.exports = {
{id: 'uses-optimized-images', weight: 0, group: 'perf-hint'},
{id: 'uses-webp-images', weight: 0, group: 'perf-hint'},
{id: 'uses-text-compression', weight: 0, group: 'perf-hint'},
{id: 'uses-rel-preconnect', weight: 0, group: 'perf-hint'},
{id: 'time-to-first-byte', weight: 0, group: 'perf-hint'},
{id: 'redirects', weight: 0, group: 'perf-hint'},
{id: 'uses-rel-preload', weight: 0, group: 'perf-hint'},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class CriticalRequestChainRenderer {
const {file, hostname} = Util.parseURL(segment.node.request.url);
const treevalEl = dom.find('.crc-node__tree-value', chainsEl);
dom.find('.crc-node__tree-file', treevalEl).textContent = `${file}`;
dom.find('.crc-node__tree-hostname', treevalEl).textContent = `(${hostname})`;
dom.find('.crc-node__tree-hostname', treevalEl).textContent = hostname ? `(${hostname})` : '';

if (!segment.hasChildren) {
const span = dom.createElement('span', 'crc-node__chain-duration');
Expand Down
4 changes: 2 additions & 2 deletions lighthouse-core/report/html/renderer/details-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ class DetailsRenderer {
let title;
try {
const parsed = Util.parseURL(url);
displayedPath = parsed.file;
displayedHost = `(${parsed.hostname})`;
displayedPath = parsed.file === '/' ? parsed.origin : parsed.file;
displayedHost = parsed.file === '/' ? '' : `(${parsed.hostname})`;
title = url;
} catch (/** @type {!Error} */ e) {
if (!(e instanceof TypeError)) {
Expand Down
16 changes: 10 additions & 6 deletions lighthouse-core/report/html/renderer/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ class Util {
name = name.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g, `$1${ELLIPSIS}`);
// Also elide other hash-like mixed-case strings
name = name.replace(/([a-zA-Z0-9-_]{9})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9-_]{10,}/g,
`$1${ELLIPSIS}`);
`$1${ELLIPSIS}`);
// Also elide long number sequences
name = name.replace(/(\d{3})\d{6,}/g, `$1${ELLIPSIS}`);
// Merge any adjacent ellipses
Expand All @@ -185,8 +185,8 @@ class Util {
const dotIndex = name.lastIndexOf('.');
if (dotIndex >= 0) {
name = name.slice(0, MAX_LENGTH - 1 - (name.length - dotIndex)) +
// Show file extension
`${ELLIPSIS}${name.slice(dotIndex)}`;
// Show file extension
`${ELLIPSIS}${name.slice(dotIndex)}`;
} else {
name = name.slice(0, MAX_LENGTH - 1) + ELLIPSIS;
}
Expand All @@ -196,13 +196,17 @@ class Util {
}

/**
* Split a URL into a file and hostname for easy display.
* Split a URL into a file, hostname and origin for easy display.
* @param {string} url
* @return {{file: string, hostname: string}}
* @return {{file: string, hostname: string, origin: string}}
*/
static parseURL(url) {
const parsedUrl = new URL(url);
return {file: Util.getURLDisplayName(parsedUrl), hostname: parsedUrl.hostname};
return {
file: Util.getURLDisplayName(parsedUrl),
hostname: parsedUrl.hostname,
origin: parsedUrl.origin,
};
}

/**
Expand Down
Loading

0 comments on commit 1176a63

Please sign in to comment.