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 audit for Date.now() usage #707

Merged
merged 5 commits into from
Sep 27, 2016
Merged
Show file tree
Hide file tree
Changes from 4 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
78 changes: 78 additions & 0 deletions lighthouse-core/audits/dobetterweb/no-datenow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* @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 Date.now() (instead of a
* newer API like performance.now()).
*/

'use strict';

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

class NoDateNowAudit extends Audit {

/**
* @return {!AuditMeta}
*/
static get meta() {
return {
category: 'JavaScript',
name: 'no-datenow',
description: 'Site does not use Date.now() in its own scripts',
helpText: 'Consider using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/now" target="_blank">performance.now()</a>, which as better precision than <code>Date.now()</code> and always increases at a constant rate, independent of the system clock.',
Copy link
Member

Choose a reason for hiding this comment

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

FWIW, this does seem like one of those tests people are going to be annoyed about if they need Date.now() for an actual timestamp since the epoch or if performance.now() overhead isn't worth it

Choose a reason for hiding this comment

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

@brendankenny not annoyed, but if not Date.now(), what should be use if what you need is not performance? Maybe lighthouse should show recommendations besides just the warning/error?

requiredArtifacts: ['URL', 'DateNowUse']
};
}

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

const pageHost = url.parse(artifacts.URL.finalUrl).host;

// Filter out Date.now() usage from scripts on other domains.
const results = artifacts.DateNowUse.errors.reduce((prev, err) => {
if (url.parse(err.url).host === pageHost) {
err.url = `${JSON.stringify(err)}`;
Copy link
Member

@brendankenny brendankenny Sep 26, 2016

Choose a reason for hiding this comment

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

you shouldn't modify the artifact itself here (and should pick a more descriptive property name once the formatter is changed)

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

prev.push(err);
}
return prev;
Copy link
Member

Choose a reason for hiding this comment

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

do you want to dedupe these so if a function calling Date.now() is itself called many times you don't get a long long list of them?

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 NoDateNowAudit.generateAuditResult({
rawValue: results.length === 0,
extendedInfo: {
formatter: Formatter.SUPPORTED_FORMATS.URLLIST,
value: results
}
});
}
}

module.exports = NoDateNowAudit;
15 changes: 12 additions & 3 deletions lighthouse-core/config/dobetterweb.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
"network": true,
"loadPage": true,
"gatherers": [
"../gather/gatherers/dobetterweb/appcache",
"../gather/gatherers/dobetterweb/websql",
"../gather/gatherers/https",
"../gather/gatherers/url"
"../gather/gatherers/url",
"../gather/gatherers/dobetterweb/appcache",
"../gather/gatherers/dobetterweb/datenow",
"../gather/gatherers/dobetterweb/websql"
]
}],

"audits": [
"../audits/dobetterweb/appcache-manifest",
"../audits/dobetterweb/no-datenow",
"../audits/dobetterweb/no-websql",
"../audits/dobetterweb/uses-http2",
"../audits/is-on-https"
Expand Down Expand Up @@ -43,6 +45,13 @@
"description": "Resources made by this application should be severed over HTTP/2 for improved performance."
}
}
}, {
"name": "Using modern JavaScript features",
"criteria": {
"no-datenow": {
"rawValue": false
}
}
}]
}]
}
5 changes: 4 additions & 1 deletion lighthouse-core/formatters/partials/url-list.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
<summary>URLs</summary>
{{#each this}}
<div class="http-resource">
<span class="http-resource__url">{{this.url}}</span><span class="http-resource__protocol">({{this.protocol}})</span>
<span class="http-resource__url">{{this.url}}</span>
Copy link
Member

Choose a reason for hiding this comment

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

Shouldn't overload url here like this. Maybe just add a place for a more general text string that is styled the same?

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

{{#if this.protocol}}
<span class="http-resource__protocol">({{this.protocol}})</span>
{{/if}}
</div>
{{/each}}
</details>
Expand Down
70 changes: 70 additions & 0 deletions lighthouse-core/gather/gatherers/dobetterweb/datenow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* @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 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 orig = Date.now;
Date.now = function() {
try {
throw Error('__called Date.now()__');
} catch (e) {
if (e.stack) {
const split = e.stack.split('\n');
Copy link
Member

Choose a reason for hiding this comment

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

HOLD UP WAIT A MINUTE

https://github.com/v8/v8/wiki/Stack-Trace-API#customizing-stack-traces

⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️ ⬆️

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

const m = split[split.length - 1].match(/(https?:\/\/.*):(\d+):(\d+)/);
Copy link
Member

Choose a reason for hiding this comment

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

I tried out this date.now monkeypatch in the console, but it led to e.stack as

"Error: __called Date.now()__
    at Error (native)
    at Function.Date.now (<anonymous>:4:13)
    at <anonymous>:1:6"

The match() then returns null. I think you could make the regex testing here a bit more liberal.

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 with the ST API

if (m) {
window.__stackTraceErrors.push({url: m[1], line: m[2], col: m[3]});
}
}
}

return orig();
};
}

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

class DateNowUse extends Gatherer {

beforePass(options) {
return options.driver.evaluateScriptOnLoad(`(${patchDateNow.toString()}())`);
}

afterPass(options) {
return options.driver.evaluateAsync(`(${collectDateNowUsage.toString()}())`)
.then(errors => {
Copy link
Member

@brendankenny brendankenny Sep 26, 2016

Choose a reason for hiding this comment

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

maybe something like dateNowUses to differentiate from the function below this handling actual errors?

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

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

module.exports = DateNowUse;
68 changes: 68 additions & 0 deletions lighthouse-core/test/audits/dobetterweb/no-datenow-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* 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 DateNowUseAudit = require('../../../audits/dobetterweb/no-datenow.js');
const assert = require('assert');

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

/* eslint-env mocha */

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

it('passes when Date.now() is not used', () => {
const auditResult = DateNowUseAudit.audit({
DateNowUse: {errors: []},
URL: {finalUrl: URL},
});
assert.equal(auditResult.rawValue, true);
assert.equal(auditResult.extendedInfo.value.length, 0);
});

it('fails when Date.now() is used on the origin', () => {
const auditResult = DateNowUseAudit.audit({
DateNowUse: {
errors: [
{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: '2'}
]
},
URL: {finalUrl: URL},
});
assert.equal(auditResult.rawValue, false);
assert.equal(auditResult.extendedInfo.value.length, 2);
});

it('passes when Date.now() is only used on a different origin', () => {
const auditResult = DateNowUseAudit.audit({
DateNowUse: {
errors: [
{url: 'http://different.com/two', line: '2', col: '2'}
]
},
URL: {finalUrl: URL},
});
assert.equal(auditResult.rawValue, true);
assert.equal(auditResult.extendedInfo.value.length, 0);
});
});