Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DBW: add console.time -> performance.mark() suggestion #712

Merged
merged 10 commits into from
Sep 28, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions lighthouse-core/audits/dobetterweb/no-console-time.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* @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.
*/

/**
* @fileoverview Audit a page to see if it's using console.time()/console.timeEnd.
*/

'use strict';

const url = require('url');
const Audit = require('../audit');
const Formatter = require('../../formatters/formatter');

class NoConsoleTimeAudit extends Audit {

/**
* @return {!AuditMeta}
*/
static get meta() {
return {
category: 'JavaScript',
name: 'no-console-time',
description: 'Site does not use console.time() in its own scripts',
helpText: 'Consider using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/User_Timing_API" target="_blank">User Timine API</a> (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark" target="_blank">performance.mark()</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure" target="_blank">performance.measure()</a>), which is a standard, uses high resolution timestamps, and has the added benefit of integrating with the DevTools timeline.',
requiredArtifacts: ['URL', 'ConsoleTimeUsage']
};
}

/**
* @param {!Artifacts} artifacts
* @return {!AuditResult}
*/
static audit(artifacts) {
if (typeof artifacts.ConsoleTimeUsage === 'undefined' ||
artifacts.ConsoleTimeUsage === -1) {
return NoConsoleTimeAudit.generateAuditResult({
rawValue: -1,
debugString: 'ConsoleTimeUsage gatherer did not run'
});
}

const pageHost = url.parse(artifacts.URL.finalUrl).host;
// Filter usage from other hosts.
const results = artifacts.ConsoleTimeUsage.usage.filter(err => {
return url.parse(err.url).host === pageHost;
}).map(err => {
return Object.assign({
misc: `(line: ${err.line}, col: ${err.col})`
}, err);
});

return NoConsoleTimeAudit.generateAuditResult({
rawValue: results.length === 0,
extendedInfo: {
formatter: Formatter.SUPPORTED_FORMATS.URLLIST,
value: results
}
});
}
}

module.exports = NoConsoleTimeAudit;
19 changes: 7 additions & 12 deletions lighthouse-core/audits/dobetterweb/no-datenow.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,13 @@ class NoDateNowAudit extends Audit {
}

const pageHost = url.parse(artifacts.URL.finalUrl).host;
// Filter out Date.now() usage if script was on another host or an error with
// the same url:line:col combo has already been seen.
const results = artifacts.DateNowUse.dateNowUses.reduce((prev, err) => {
const jsonStr = JSON.stringify(err);
if (url.parse(err.url).host === pageHost && prev.indexOf(jsonStr) === -1) {
prev.push(jsonStr);
}
return prev;
}, []).map(err => {
err = JSON.parse(err);
err.misc = `(line: ${err.line}, col: ${err.col})`;
return err;
// Filter usage from other hosts.
const results = artifacts.DateNowUse.usage.filter(err => {
return url.parse(err.url).host === pageHost;
}).map(err => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

return Object.assign({
misc: `(line: ${err.line}, col: ${err.col})`
}, err);
});

return NoDateNowAudit.generateAuditResult({
Expand Down
5 changes: 5 additions & 0 deletions lighthouse-core/config/dobetterweb.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
"../gather/gatherers/https",
"../gather/gatherers/url",
"../gather/gatherers/dobetterweb/appcache",
"../gather/gatherers/dobetterweb/console-time-usage",
"../gather/gatherers/dobetterweb/datenow",
"../gather/gatherers/dobetterweb/websql"
]
}],

"audits": [
"../audits/dobetterweb/appcache-manifest",
"../audits/dobetterweb/no-console-time",
"../audits/dobetterweb/no-datenow",
"../audits/dobetterweb/no-websql",
"../audits/dobetterweb/uses-http2",
Expand Down Expand Up @@ -50,6 +52,9 @@
"criteria": {
"no-datenow": {
"rawValue": false
},
"no-console-time": {
"rawValue": false
}
}
}]
Expand Down
54 changes: 54 additions & 0 deletions lighthouse-core/gather/drivers/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,37 @@ const log = require('../../lib/log.js');
const MAX_WAIT_FOR_LOAD_EVENT = 25 * 1000;
const PAUSE_AFTER_LOAD = 500;

/**
* Tracks function call usage. Used by captureJSCalls to inject code into the page.
* @param {function(...*): *} funcRef The function call to track.
* @param {!Set} set An empty set to populate with stack traces. Should be
* on the global object.
* @return {function(...*): *} A wrapper around the original function.
*/
function captureJSCallUsage(funcRef, set) {
const originalFunc = funcRef;
const originalPrepareStackTrace = Error.prepareStackTrace;

return function() {
// See v8's Stack Trace API https://github.com/v8/v8/wiki/Stack-Trace-API#customizing-stack-traces
Error.prepareStackTrace = function(error, structStackTrace) {
const lastCallFrame = structStackTrace[structStackTrace.length - 1];
const file = lastCallFrame.getFileName();
const line = lastCallFrame.getLineNumber();
const col = lastCallFrame.getColumnNumber();
return {url: file, line, col}; // return value is e.stack
};
const e = new Error(`__called ${funcRef.name}__`);
set.add(JSON.stringify(e.stack));

// Restore prepareStackTrace so future errors use v8's formatter and not
// our custom one.
Error.prepareStackTrace = originalPrepareStackTrace;

return originalFunc.apply(this, arguments);
};
}

class Driver {

constructor() {
Expand Down Expand Up @@ -447,6 +478,29 @@ class Driver {
storageTypes: 'all',
});
}

/**
* Keeps track of calls to a JS function and returns a list of {url, line, col}
* of the usage. Should be called before page load (in beforePass).
* @param {string} funcName The function name to track ('Date.now', 'console.time').
* @return {function(): !Promise<!Array<{url: string, line: number, col: number}>>}
* Call this method when you want results.
*/
captureFunctionCallSites(funcName) {
const globalVarToPopulate = `window['__${funcName}StackTraces']`;
const collectUsage = () => {
return this.evaluateAsync(
`__returnResults(Array.from(${globalVarToPopulate}).map(item => JSON.parse(item)))`);
};

const funcBody = captureJSCallUsage.toString();

this.evaluateScriptOnLoad(`
Copy link
Member

@paulirish paulirish Sep 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm having a hard time parsing this magic. can we split it out a tad more?

I think this is basically what we're doing, eh?

 this.evaluateScriptOnLoad(`
        ${variableToPopulate} = new Set();
        function ${Driver.captureUsage.toString()};
        ${funcVar} = ${Driver.captureUsage.name}(${funcVar}, ${variableToPopulate});
`);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slightly more important is renaming funcVar to funcName since it's in string form until the template literal is evaluated

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

${globalVarToPopulate} = new Set();
(${funcName} = ${funcBody}(${funcName}, ${globalVarToPopulate}))`);

return collectUsage;
}
}

module.exports = Driver;
Expand Down
42 changes: 42 additions & 0 deletions lighthouse-core/gather/gatherers/dobetterweb/console-time-usage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* @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.
*/

/**
* @fileoverview Tests whether the page is using console.time().
*/

'use strict';

const Gatherer = require('../gatherer');

class ConsoleTimeUsage extends Gatherer {

beforePass(options) {
this.collectUsage = options.driver.captureFunctionCallSites('console.time');
}

afterPass() {
return this.collectUsage().then(consoleTimeUsage => {
this.artifact.usage = consoleTimeUsage;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do these have to saved on this.artifact.usage? Could also just save on this.artifact itself

Copy link
Contributor Author

@ebidel ebidel Sep 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the consistency between audits of this natural. Always accessing the same .usage array.

}, _ => {
this.artifact = -1;
return;
});
}
}

module.exports = ConsoleTimeUsage;
45 changes: 8 additions & 37 deletions lighthouse-core/gather/gatherers/dobetterweb/datenow.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,52 +19,23 @@
* @fileoverview Tests whether the page is using Date.now().
*/

/* global window, __returnResults */

'use strict';

const Gatherer = require('../gatherer');

function patchDateNow() {
window.__stackTraceErrors = [];
// Override Date.now() so we know when if it's called.
const origDateNow = Date.now;
const originalPrepareStackTrace = Error.prepareStackTrace;
Date.now = function() {
// See v8's Stack Trace API https://github.com/v8/v8/wiki/Stack-Trace-API#customizing-stack-traces
Error.prepareStackTrace = function(error, structStackTrace) {
const lastCallFrame = structStackTrace[structStackTrace.length - 1];
const file = lastCallFrame.getFileName();
const line = lastCallFrame.getLineNumber();
const col = lastCallFrame.getColumnNumber();
window.__stackTraceErrors.push({url: file, line, col});
return {url: file, line, col}; // return value populates e.stack.
};
Error.captureStackTrace(new Error('__called Date.now()__'));
// Remove custom formatter so future results use v8's formatter.
Error.prepareStackTrace = originalPrepareStackTrace;
return origDateNow();
};
}

function collectDateNowUsage() {
__returnResults(window.__stackTraceErrors);
}

class DateNowUse extends Gatherer {

beforePass(options) {
return options.driver.evaluateScriptOnLoad(`(${patchDateNow.toString()}())`);
this.collectUsage = options.driver.captureFunctionCallSites('Date.now');
}

afterPass(options) {
return options.driver.evaluateAsync(`(${collectDateNowUsage.toString()}())`)
.then(dateNowUses => {
this.artifact.dateNowUses = dateNowUses;
}, _ => {
this.artifact = -1;
return;
});
afterPass() {
return this.collectUsage().then(dateNowUses => {
this.artifact.usage = dateNowUses;
}, _ => {
this.artifact = -1;
return;
});
}
}

Expand Down
69 changes: 69 additions & 0 deletions lighthouse-core/test/audits/dobetterweb/no-console-time-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* 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 NoConsoleTimeAudit = require('../../../audits/dobetterweb/no-console-time.js');
const assert = require('assert');

const URL = 'https://example.com';

/* eslint-env mocha */

describe('Page does not use console.time()', () => {
it('fails when no input present', () => {
const auditResult = NoConsoleTimeAudit.audit({});
assert.equal(auditResult.rawValue, -1);
assert.ok(auditResult.debugString);
});

it('passes when console.time() is not used', () => {
const auditResult = NoConsoleTimeAudit.audit({
ConsoleTimeUsage: {usage: []},
URL: {finalUrl: URL},
});
assert.equal(auditResult.rawValue, true);
assert.equal(auditResult.extendedInfo.value.length, 0);
});

it('passes when console.time() is used on a different origin', () => {
const auditResult = NoConsoleTimeAudit.audit({
ConsoleTimeUsage: {
usage: [
{url: 'http://different.com/two', line: 2, col: 2},
{url: 'http://example2.com/two', line: 2, col: 22}
]
},
URL: {finalUrl: URL},
});
assert.equal(auditResult.rawValue, true);
assert.equal(auditResult.extendedInfo.value.length, 0);
});

it('fails when console.time() is used on the origin', () => {
const auditResult = NoConsoleTimeAudit.audit({
ConsoleTimeUsage: {
usage: [
{url: 'http://example.com/one', line: 1, col: 1},
{url: 'http://example.com/two', line: 10, col: 1},
{url: 'http://example2.com/two', line: 2, col: 22}
]
},
URL: {finalUrl: URL},
});
assert.equal(auditResult.rawValue, false);
assert.equal(auditResult.extendedInfo.value.length, 2);
});
});
Loading