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

core(gather-runner): always reset scroll position #9060

Merged
merged 4 commits into from
Jun 7, 2019
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
1 change: 0 additions & 1 deletion lighthouse-core/config/default-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ const defaultConfig = {
'seo/embedded-content',
'seo/robots-txt',
'seo/tap-targets',
// Always run axe last because it scrolls the page down to the bottom
'accessibility',
],
},
Expand Down
41 changes: 40 additions & 1 deletion lighthouse-core/gather/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ class Driver {
this._handleReceivedMessageFromTarget(event, []).catch(this._handleEventError);
});

// We use isolated execution contexts for `evaluateAsync` that can be destroyed through navigation
// and other page actions. Cleanup our relevant bookkeeping as we see those events.
this.on('Runtime.executionContextDestroyed', event => {
if (event.executionContextId === this._isolatedExecutionContextId) {
this._clearIsolatedContextId();
}
});

this.on('Page.frameNavigated', () => this._clearIsolatedContextId());

connection.on('protocolevent', this._handleProtocolEvent.bind(this));

/**
Expand Down Expand Up @@ -464,7 +474,20 @@ class Driver {
*/
async evaluateAsync(expression, options = {}) {
const contextId = options.useIsolation ? await this._getOrCreateIsolatedContextId() : undefined;
return this._evaluateInContext(expression, contextId);

try {
// `await` is not redunant here because we want to `catch` the async errors
return await this._evaluateInContext(expression, contextId);
} catch (err) {
// If we were using isolation and the context disappeared on us, retry one more time.
if (contextId && err.message.includes('Cannot find context')) {
Copy link
Member

Choose a reason for hiding this comment

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

is this still needed given the new event handling?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I'm not sure what you mean by new event handling, but it's something we should do regardless. Our temporary context can be destroyed at any time and we used to see high volumes of this in sentry once upon a time.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Oh do you just mean Runtime.executionContextDestroyed? It can still race if we're trying to eval this between when we receive the context destroyed event and we eval this, plus the aforementioned destroying of our context regardless of navigation :)

Copy link
Member

Choose a reason for hiding this comment

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

Oh do you just mean Runtime.executionContextDestroyed? It can still race

yeah, I guess it feels like we should be handling it the "correct way"™ or the "sloppily but effectively prevent race conditions way", but not both, but w/e :)

this._clearIsolatedContextId();
const freshContextId = await this._getOrCreateIsolatedContextId();
return this._evaluateInContext(expression, freshContextId);
}

throw err;
}
}

/**
Expand Down Expand Up @@ -1324,6 +1347,22 @@ class Driver {
return flattenedDocument.nodes ? flattenedDocument.nodes : [];
}

/**
* @param {{x: number, y: number}} position
* @return {Promise<void>}
*/
scrollTo(position) {
const scrollExpression = `window.scrollTo(${position.x}, ${position.y})`;
return this.evaluateAsync(scrollExpression, {useIsolation: true});
Copy link
Member

Choose a reason for hiding this comment

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

feels like the protocol should have somethign for this too, but I don't see anything

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

You can synthesize a gesture but that's not what we want to do https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-synthesizeScrollGesture

Copy link
Member

Choose a reason for hiding this comment

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

You can synthesize a gesture but that's not what we want to do

yeah, I meant it feels like there should be a method :)

Copy link
Member

Choose a reason for hiding this comment

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

apparently this is exactly what devtools does (e.g. "Scroll into view" in the devtools panel just remote evals scrollIntoViewIfNeeded(true) on the selected element) so we're in good company :)

}

/**
* @return {Promise<{x: number, y: number}>}
*/
getScrollPosition() {
return this.evaluateAsync(`({x: window.scrollX, y: window.scrollY})`, {useIsolation: true});
Copy link
Member

Choose a reason for hiding this comment

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

feels like the protocol should have something for this...Page.getLayoutMetrics?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

not that I can find

image

image

Copy link
Member

Choose a reason for hiding this comment

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

looks like it's Page.getLayoutMetrics -> response.visualViewport.pageX and pageY, but it's possible in the end that it's worse perf than this evaluateAsync

}

/**
* @param {{additionalTraceCategories?: string|null}=} settings
* @return {Promise<void>}
Expand Down
6 changes: 6 additions & 0 deletions lighthouse-core/gather/gather-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -318,12 +318,17 @@ class GatherRunner {
* @return {Promise<void>}
*/
static async afterPass(passContext, loadData, gathererResults) {
const driver = passContext.driver;
const config = passContext.passConfig;
const gatherers = config.gatherers;

const apStatus = {msg: `Running afterPass methods`, id: `lh:gather:afterPass`};
log.time(apStatus, 'verbose');

// Some gatherers scroll the page which can cause unexpected results for other gatherers.
// We reset the scroll position in between each gatherer.
const scrollPosition = await driver.getScrollPosition();

for (const gathererDefn of gatherers) {
const gatherer = gathererDefn.instance;
const status = {
Expand All @@ -341,6 +346,7 @@ class GatherRunner {
gathererResult.push(artifactPromise);
gathererResults[gatherer.name] = gathererResult;
await artifactPromise.catch(() => {});
await driver.scrollTo(scrollPosition);
log.timeEnd(status);
}
log.timeEnd(apStatus);
Expand Down
13 changes: 13 additions & 0 deletions lighthouse-core/test/gather/driver-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,19 @@ describe('.evaluateAsync', () => {
expect.anything()
);
});

it('recovers from isolation failures', async () => {
connectionStub.sendCommand = createMockSendCommandFn()
.mockResponse('Page.getResourceTree', {frameTree: {frame: {id: 1337}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 9001})
.mockResponse('Runtime.evaluate', Promise.reject(new Error('Cannot find context')))
.mockResponse('Page.getResourceTree', {frameTree: {frame: {id: 1337}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 9002})
.mockResponse('Runtime.evaluate', {result: {value: 'mocked value'}});

const value = await driver.evaluateAsync('"magic"', {useIsolation: true});
expect(value).toEqual('mocked value');
});
});

describe('.sendCommand', () => {
Expand Down
9 changes: 9 additions & 0 deletions lighthouse-core/test/gather/fake-driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
'use strict';

function makeFakeDriver({protocolGetVersionResponse}) {
let scrollPosition = {x: 0, y: 0};

return {
getBrowserVersion() {
return Promise.resolve(Object.assign({}, protocolGetVersionResponse, {milestone: 71}));
Expand Down Expand Up @@ -57,6 +59,13 @@ function makeFakeDriver({protocolGetVersionResponse}) {
evaluateAsync() {
return Promise.resolve({});
},
scrollTo(position) {
scrollPosition = position;
return Promise.resolve();
},
getScrollPosition() {
return Promise.resolve(scrollPosition);
},
registerPerformanceObserver() {
return Promise.resolve();
},
Expand Down
30 changes: 30 additions & 0 deletions lighthouse-core/test/gather/gather-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,8 @@ describe('GatherRunner', function() {
endTrace: asyncFunc,
endDevtoolsLog: () => [],
getBrowserVersion: async () => ({userAgent: ''}),
getScrollPosition: async () => 1,
scrollTo: async () => {},
};
const passConfig = {
passName: 'default',
Expand Down Expand Up @@ -588,6 +590,34 @@ describe('GatherRunner', function() {
});
});

it('resets scroll position between every gatherer', async () => {
class ScrollMcScrollyGatherer extends TestGatherer {
afterPass(context) {
context.driver.scrollTo({x: 1000, y: 1000});
}
}

const url = 'https://example.com';
const driver = Object.assign({}, fakeDriver);
const scrollToSpy = jest.spyOn(driver, 'scrollTo');

const passConfig = {
recordTrace: true,
gatherers: [
{instance: new ScrollMcScrollyGatherer()},
{instance: new TestGatherer()},
],
};

await GatherRunner.afterPass({url, driver, passConfig}, {}, {TestGatherer: []});
// One time for the afterPass of ScrollMcScrolly, two times for the resets of the two gatherers.
expect(scrollToSpy.mock.calls).toEqual([
[{x: 1000, y: 1000}],
[{x: 0, y: 0}],
[{x: 0, y: 0}],
]);
});

it('does as many passes as are required', () => {
const t1 = new TestGatherer();
const t2 = new TestGatherer();
Expand Down