Skip to content

Commit

Permalink
core(fr): extract driver preparation methods (#12445)
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickhulce authored and paulirish committed May 12, 2021
1 parent b080e30 commit acc68c0
Show file tree
Hide file tree
Showing 9 changed files with 562 additions and 278 deletions.
35 changes: 0 additions & 35 deletions lighthouse-core/gather/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ const log = require('lighthouse-logger');
const DevtoolsLog = require('./devtools-log.js');
const TraceGatherer = require('./gatherers/trace.js');

const pageFunctions = require('../lib/page-functions.js');

// Pulled in for Connection type checking.
// eslint-disable-next-line no-unused-vars
const Connection = require('./connections/connection.js');
Expand Down Expand Up @@ -462,39 +460,6 @@ class Driver {
this._devtoolsLog.endRecording();
return this._devtoolsLog.messages;
}

/**
* Use a RequestIdleCallback shim for tests run with simulated throttling, so that the deadline can be used without
* a penalty
* @param {LH.Config.Settings} settings
* @return {Promise<void>}
*/
async registerRequestIdleCallbackWrap(settings) {
if (settings.throttlingMethod === 'simulate') {
await this.executionContext.evaluateOnNewDocument(
pageFunctions.wrapRequestIdleCallback,
{args: [settings.throttling.cpuSlowdownMultiplier]}
);
}
}

/**
* Dismiss JavaScript dialogs (alert, confirm, prompt), providing a
* generic promptText in case the dialog is a prompt.
* @return {Promise<void>}
*/
async dismissJavaScriptDialogs() {
this.on('Page.javascriptDialogOpening', data => {
log.warn('Driver', `${data.type} dialog opened by the page automatically suppressed.`);

this.sendCommand('Page.handleJavaScriptDialog', {
accept: true,
promptText: 'Lighthouse prompt response',
}).catch(err => log.warn('Driver', err));
});

await this.sendCommand('Page.enable');
}
}

module.exports = Driver;
177 changes: 177 additions & 0 deletions lighthouse-core/gather/driver/prepare.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/**
* @license Copyright 2021 The Lighthouse Authors. 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 log = require('lighthouse-logger');
const storage = require('./storage.js');
const emulation = require('../../lib/emulation.js');
const pageFunctions = require('../../lib/page-functions.js');

/**
* Enables `Debugger` domain to receive async stacktrace information on network request initiators.
* This is critical for tracking attribution of tasks and performance simulation accuracy.
* @param {LH.Gatherer.FRProtocolSession} session
*/
async function enableAsyncStacks(session) {
const enable = async () => {
await session.sendCommand('Debugger.enable');
await session.sendCommand('Debugger.setSkipAllPauses', {skip: true});
await session.sendCommand('Debugger.setAsyncCallStackDepth', {maxDepth: 8});
};

// Resume any pauses that make it through `setSkipAllPauses`
session.on('Debugger.paused', () => session.sendCommand('Debugger.resume'));

// `Debugger.setSkipAllPauses` is reset after every navigation, so retrigger it on main frame navigations.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=990945&q=setSkipAllPauses&can=2
session.on('Page.frameNavigated', event => {
if (event.frame.parentId) return;
enable().catch(err => log.error('Driver', err));
});

await enable();
}

/**
* Use a RequestIdleCallback shim for tests run with simulated throttling, so that the deadline can be used without
* a penalty.
* @param {LH.Gatherer.FRTransitionalDriver} driver
* @param {LH.Config.Settings} settings
* @return {Promise<void>}
*/
async function shimRequestIdleCallbackOnNewDocument(driver, settings) {
await driver.executionContext.evaluateOnNewDocument(pageFunctions.wrapRequestIdleCallback, {
args: [settings.throttling.cpuSlowdownMultiplier],
});
}

/**
* Dismiss JavaScript dialogs (alert, confirm, prompt), providing a
* generic promptText in case the dialog is a prompt.
* @param {LH.Gatherer.FRProtocolSession} session
* @return {Promise<void>}
*/
async function dismissJavaScriptDialogs(session) {
session.on('Page.javascriptDialogOpening', data => {
log.warn('Driver', `${data.type} dialog opened by the page automatically suppressed.`);

session
.sendCommand('Page.handleJavaScriptDialog', {
accept: true,
promptText: 'Lighthouse prompt response',
})
.catch(err => log.warn('Driver', err));
});

await session.sendCommand('Page.enable');
}

/**
* @param {LH.Gatherer.FRProtocolSession} session
* @param {{url: string}} navigation
* @return {Promise<{warnings: Array<LH.IcuMessage>}>}
*/
async function resetStorageForNavigation(session, navigation) {
/** @type {Array<LH.IcuMessage>} */
const warnings = [];

// Reset the storage and warn if there appears to be other important data.
const warning = await storage.getImportantStorageWarning(session, navigation.url);
if (warning) warnings.push(warning);
await storage.clearDataForOrigin(session, navigation.url);
await storage.clearBrowserCaches(session);

return {warnings};
}

/**
* Prepares a target for a particular navigation by resetting storage and setting throttling.
*
* This method assumes `prepareTargetForNavigationMode` has already been invoked.
*
* @param {LH.Gatherer.FRProtocolSession} session
* @param {LH.Config.Settings} settings
* @param {Pick<LH.Config.NavigationDefn, 'disableThrottling'|'disableStorageReset'|'blockedUrlPatterns'> & {url: string}} navigation
*/
async function prepareNetworkForNavigation(session, settings, navigation) {
const status = {msg: 'Preparing network conditions', id: `lh:gather:prepareNetworkForNavigation`};
log.time(status);

if (navigation.disableThrottling) await emulation.clearThrottling(session);
else await emulation.throttle(session, settings);

// Set request blocking before any network activity.
// No "clearing" is done at the end of the navigation since Network.setBlockedURLs([]) will unset all if
// neccessary at the beginning of the next navigation.
const blockedUrls = (navigation.blockedUrlPatterns || []).concat(
settings.blockedUrlPatterns || []
);
await session.sendCommand('Network.setBlockedURLs', {urls: blockedUrls});

const headers = settings.extraHeaders;
if (headers) await session.sendCommand('Network.setExtraHTTPHeaders', {headers});

log.timeEnd(status);
}

/**
* Prepares a target to be analyzed in navigation mode by enabling protocol domains, emulation, and new document
* handlers for global APIs or error handling.
*
* This method should be used in combination with `prepareTargetForIndividualNavigation` before a specific navigation occurs.
*
* @param {LH.Gatherer.FRTransitionalDriver} driver
* @param {LH.Config.Settings} settings
*/
async function prepareTargetForNavigationMode(driver, settings) {
// Emulate our target device screen and user agent.
await emulation.emulate(driver.defaultSession, settings);

// Enable better stacks on network requests.
await enableAsyncStacks(driver.defaultSession);

// Automatically handle any JavaScript dialogs to prevent a hung renderer.
await dismissJavaScriptDialogs(driver.defaultSession);

// Inject our snippet to cache important web platform APIs before they're (possibly) ponyfilled by the page.
await driver.executionContext.cacheNativesOnNewDocument();

// Wrap requestIdleCallback so pages under simulation receive the correct rIC deadlines.
if (settings.throttlingMethod === 'simulate') {
await shimRequestIdleCallbackOnNewDocument(driver, settings);
}
}

/**
* Prepares a target for a particular navigation by resetting storage and setting network.
*
* This method assumes `prepareTargetForNavigationMode` has already been invoked.
*
* @param {LH.Gatherer.FRProtocolSession} session
* @param {LH.Config.Settings} settings
* @param {Pick<LH.Config.NavigationDefn, 'disableThrottling'|'disableStorageReset'|'blockedUrlPatterns'> & {url: string}} navigation
* @return {Promise<{warnings: Array<LH.IcuMessage>}>}
*/
async function prepareTargetForIndividualNavigation(session, settings, navigation) {
/** @type {Array<LH.IcuMessage>} */
const warnings = [];

const shouldResetStorage = !settings.disableStorageReset && !navigation.disableStorageReset;
if (shouldResetStorage) {
const {warnings: storageWarnings} = await resetStorageForNavigation(session, navigation);
warnings.push(...storageWarnings);
}

await prepareNetworkForNavigation(session, settings, navigation);

return {warnings};
}

module.exports = {
prepareNetworkForNavigation,
prepareTargetForNavigationMode,
prepareTargetForIndividualNavigation,
};
6 changes: 3 additions & 3 deletions lighthouse-core/gather/driver/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ async function getImportantStorageWarning(session, url) {
* @param {LH.Gatherer.FRProtocolSession} session
* @return {Promise<void>}
*/
async function cleanBrowserCaches(session) {
const status = {msg: 'Cleaning browser cache', id: 'lh:storage:cleanBrowserCaches'};
async function clearBrowserCaches(session) {
const status = {msg: 'Cleaning browser cache', id: 'lh:storage:clearBrowserCaches'};
log.time(status);

// Wipe entire disk cache
Expand All @@ -115,7 +115,7 @@ async function cleanBrowserCaches(session) {

module.exports = {
clearDataForOrigin,
cleanBrowserCaches,
clearBrowserCaches,
getImportantStorageWarning,
UIStrings,
};
89 changes: 15 additions & 74 deletions lighthouse-core/gather/gather-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const constants = require('../config/constants.js');
const i18n = require('../lib/i18n/i18n.js');
const URL = require('../lib/url-shim.js');
const {getBenchmarkIndex} = require('./driver/environment.js');
const prepare = require('./driver/prepare.js');
const storage = require('./driver/storage.js');
const navigation = require('./driver/navigation.js');
const serviceWorkers = require('./driver/service-workers.js');
Expand Down Expand Up @@ -174,46 +175,19 @@ class GatherRunner {
/**
* @param {Driver} driver
* @param {{requestedUrl: string, settings: LH.Config.Settings}} options
* @param {(string | LH.IcuMessage)[]} LighthouseRunWarnings
* @return {Promise<void>}
*/
static async setupDriver(driver, options, LighthouseRunWarnings) {
static async setupDriver(driver, options) {
const status = {msg: 'Initializing…', id: 'lh:gather:setupDriver'};
log.time(status);
const resetStorage = !options.settings.disableStorageReset;
const session = driver.defaultSession;

// Assert no service workers are still installed, so we test that they would actually be installed for a new user.
// TODO(FR-COMPAT): re-evaluate the necessity of this check
await GatherRunner.assertNoSameOriginServiceWorkerClients(session, options.requestedUrl);

// Emulate our target device screen and user agent.
await emulation.emulate(driver.defaultSession, options.settings);
await prepare.prepareTargetForNavigationMode(driver, options.settings);

// Enable `Debugger` domain to receive async stacktrace information on network request initiators.
// This is critical for tracing certain performance simulation situations.
session.on('Debugger.paused', () => session.sendCommand('Debugger.resume'));
await session.sendCommand('Debugger.enable');
await session.sendCommand('Debugger.setSkipAllPauses', {skip: true});
await session.sendCommand('Debugger.setAsyncCallStackDepth', {maxDepth: 8});

// Inject our snippet to cache important web platform APIs before they're (possibly) ponyfilled by the page.
await driver.executionContext.cacheNativesOnNewDocument();

// Automatically handle any JavaScript dialogs to prevent a hung renderer.
await driver.dismissJavaScriptDialogs();

// Wrap requestIdleCallback so pages under simulation receive the correct rIC deadlines.
await driver.registerRequestIdleCallbackWrap(options.settings);

// Reset the storage and warn if there appears to be other important data.
if (resetStorage) {
const warning = await storage.getImportantStorageWarning(session, options.requestedUrl);
if (warning) {
LighthouseRunWarnings.push(warning);
}
await storage.clearDataForOrigin(session, options.requestedUrl);
}
log.timeEnd(status);
}

Expand Down Expand Up @@ -407,35 +381,6 @@ class GatherRunner {
return str_(UIStrings.warningSlowHostCpu);
}

/**
* Initialize network settings for the pass, e.g. throttling, blocked URLs,
* and manual request headers.
* @param {LH.Gatherer.PassContext} passContext
* @return {Promise<void>}
*/
static async setupPassNetwork(passContext) {
const status = {msg: 'Setting up network for the pass trace', id: `lh:gather:setupPassNetwork`};
log.time(status);

const session = passContext.driver.defaultSession;
const passConfig = passContext.passConfig;
if (passConfig.useThrottling) await emulation.throttle(session, passContext.settings);
else await emulation.clearThrottling(session);

const blockedUrls = (passContext.passConfig.blockedUrlPatterns || [])
.concat(passContext.settings.blockedUrlPatterns || []);

// Set request blocking before any network activity
// No "clearing" is done at the end of the pass since Network.setBlockedURLs([]) will unset all if
// neccessary at the beginning of the next pass.
await session.sendCommand('Network.setBlockedURLs', {urls: blockedUrls});

const headers = passContext.settings.extraHeaders;
if (headers) await session.sendCommand('Network.setExtraHTTPHeaders', {headers});

log.timeEnd(status);
}

/**
* Beging recording devtoolsLog and trace (if requested).
* @param {LH.Gatherer.PassContext} passContext
Expand Down Expand Up @@ -728,7 +673,7 @@ class GatherRunner {
const baseArtifacts = await GatherRunner.initializeBaseArtifacts(options);
baseArtifacts.BenchmarkIndex = await getBenchmarkIndex(driver.executionContext);

await GatherRunner.setupDriver(driver, options, baseArtifacts.LighthouseRunWarnings);
await GatherRunner.setupDriver(driver, options);

let isFirstPass = true;
for (const passConfig of passConfigs) {
Expand Down Expand Up @@ -774,17 +719,6 @@ class GatherRunner {
}
}

/**
* Returns whether this pass should clear the caches.
* Only if it is a performance run and the settings don't disable it.
* @param {LH.Gatherer.PassContext} passContext
* @return {boolean}
*/
static shouldClearCaches(passContext) {
const {settings, passConfig} = passContext;
return !settings.disableStorageReset && passConfig.recordTrace && passConfig.useThrottling;
}

/**
* Save the devtoolsLog and trace (if applicable) to baseArtifacts.
* @param {LH.Gatherer.PassContext} passContext
Expand Down Expand Up @@ -816,10 +750,17 @@ class GatherRunner {

// Go to about:blank, set up, and run `beforePass()` on gatherers.
await GatherRunner.loadBlank(driver, passConfig.blankPage);
await GatherRunner.setupPassNetwork(passContext);
if (GatherRunner.shouldClearCaches(passContext)) {
await storage.cleanBrowserCaches(driver.defaultSession); // Clear disk & memory cache if it's a perf run
}
const {warnings} = await prepare.prepareTargetForIndividualNavigation(
driver.defaultSession,
passContext.settings,
{
url: passContext.url,
disableStorageReset: !passConfig.useThrottling,
disableThrottling: !passConfig.useThrottling,
blockedUrlPatterns: passConfig.blockedUrlPatterns,
}
);
passContext.LighthouseRunWarnings.push(...warnings);
await GatherRunner.beforePass(passContext, gathererResults);

// Navigate, start recording, and run `pass()` on gatherers.
Expand Down

0 comments on commit acc68c0

Please sign in to comment.