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

Add a separate proxy for WDA commands without session ID #395

Merged
merged 5 commits into from
Mar 15, 2017
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
2 changes: 1 addition & 1 deletion lib/commands/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ commands.background = async function (duration) {
'The \'timeout\' attribute can be \'null\' or any negative number to put the app under test ' +
'into background and never come back or a positive number of milliseconds to wait until the app is restored.');
}
return await this.proxyCommand(endpoint, 'POST', params);
return await this.proxyCommand(endpoint, 'POST', params, endpoint !== homescreenEndpoint);
};

/*
Expand Down
16 changes: 10 additions & 6 deletions lib/commands/proxy-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const GET_STATUS_COMMAND = 'getStatus';

let helpers = {}, extensions = {};

helpers.proxyCommand = async function (endpoint, method, body) {
helpers.proxyCommand = async function (endpoint, method, body, isSessionCommand = true) {
if (this.shutdownUnexpectedly) return;

if (!endpoint) {
Expand All @@ -16,8 +16,12 @@ helpers.proxyCommand = async function (endpoint, method, body) {
log.errorAndThrow(`Proxying only works for the following requests: ${SUPPORTED_METHODS.join(', ')}`);
}

if (!this.wda || !this.wda.jwproxy) {
throw new Error("Can't call proxyCommand without proxy active");
if (!this.wda) {
throw new Error("Can't call proxyCommand without WDA driver active");
}
const proxy = isSessionCommand ? this.wda.jwproxy : this.wda.noSessionProxy;
if (!proxy) {
throw new Error("Can't call proxyCommand without WDA proxy active");
}

const cmdName = routeToCommandName(endpoint, method);
Expand All @@ -26,19 +30,19 @@ helpers.proxyCommand = async function (endpoint, method, body) {
if (timeout) {
log.debug(`Setting custom timeout to ${timeout} ms for "${cmdName}" command`);
let isCommandExpired = false;
res = await B.Promise.resolve(this.wda.jwproxy.command(endpoint, method, body))
res = await B.Promise.resolve(proxy.command(endpoint, method, body))
.timeout(timeout)
.catch(B.Promise.TimeoutError, () => {
isCommandExpired = true;
});
if (isCommandExpired) {
this.wda.jwproxy.cancelActiveRequests();
proxy.cancelActiveRequests();
const errMsg = `Appium did not get any response from "${cmdName}" command in ${timeout} ms`;
await this.startUnexpectedShutdown(new errors.TimeoutError(errMsg));
log.errorAndThrow(errMsg);
}
} else {
res = await this.wda.jwproxy.command(endpoint, method, body);
res = await proxy.command(endpoint, method, body);
}

// temporarily handle errors that can be returned
Expand Down
34 changes: 34 additions & 0 deletions lib/no-session-proxy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { util } from 'appium-support';
import { JWProxy } from 'appium-base-driver';

class NoSessionProxy extends JWProxy {
constructor (opts = {}) {
super(opts);
}

getUrlForProxy (url) {
if (url === '') {
url = '/';
}
const proxyBase = `${this.scheme}://${this.server}:${this.port}${this.base}`;
let remainingUrl = '';
if ((new RegExp('^/')).test(url)) {
remainingUrl = url;
} else {
throw new Error(`Did not know what to do with url '${url}'`);
}
remainingUrl = remainingUrl.replace(/\/$/, ''); // can't have trailing slashes
return proxyBase + remainingUrl;
}

async proxyReqRes (req, res) {
let [response, body] = await this.proxy(req.originalUrl, req.method, req.body);
res.headers = response.headers;
res.set('Content-type', response.headers['content-type']);
body = util.safeJsonParse(body);
res.status(response.statusCode).send(JSON.stringify(body));
}
}

export { NoSessionProxy };
export default NoSessionProxy;
36 changes: 18 additions & 18 deletions lib/webdriveragent.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { SubProcess } from 'teen_process';
import { JWProxy } from 'appium-base-driver';
import { fs, logger } from 'appium-support';
import log from './logger';
import { NoSessionProxy } from "./no-session-proxy";
import { killAppUsingAppName, generateXcodeConfigFile } from './utils.js';
import request from 'request-promise';
import { updateProjectFile, resetProjectFile, checkForDependencies,
setRealDeviceSecurity, fixXCUICoordinateFile } from './webdriveragent-utils';

Expand Down Expand Up @@ -80,12 +80,14 @@ class WebDriverAgent {
if (this.webDriverAgentUrl) {
log.info(`Using provided WebdriverAgent at '${this.webDriverAgentUrl}'`);
this.url = this.webDriverAgentUrl;
this.setupProxy(sessionId);
this.setupProxies(sessionId);
return this.webDriverAgentUrl;
}

log.info('Launching WebDriverAgent on the device');

this.setupProxies(sessionId);

if (!await fs.exists(this.agentPath)) {
throw new Error(`Trying to use WebDriverAgent project at '${this.agentPath}' but the ` +
'file does not exist');
Expand Down Expand Up @@ -129,21 +131,24 @@ class WebDriverAgent {
await this.startiproxy();
}

this.setupProxy(sessionId);

// start the xcodebuild process
return await this.startXcodebuild();
}

setupProxy (sessionId) {
this.jwproxy = new JWProxy({
setupProxies (sessionId) {
const proxyOpts = {
server: this.url.hostname,
port: this.url.port,
base: '',
timeout: this.wdaConnectionTimeout,
});
};

this.jwproxy = new JWProxy(proxyOpts);
this.jwproxy.sessionId = sessionId;
this.proxyReqRes = this.jwproxy.proxyReqRes.bind(this.jwproxy);

this.noSessionProxy = new NoSessionProxy(proxyOpts);
this.noSessionProxyReqRes = this.noSessionProxy.proxyReqRes.bind(this.noSessionProxy);
}

getXcodeBuildCommand (buildOnly = false) {
Expand Down Expand Up @@ -302,18 +307,13 @@ class WebDriverAgent {
return;
}
try {
let opts = {
method: 'GET',
uri: `${this.url.href}status`,
headers: 'Content-Type: application/json;charset=UTF-8, accept: application/json',
forever: true,
json: true,
};
let res = await request(opts);
if (res.status !== 0) {
throw new Error(`Received non-zero status code from WDA server: '${res.status}'`);
const proxyTimeout = this.noSessionProxy.timeout;
try {
this.noSessionProxy.timeout = 1000;
currentStatus = await this.noSessionProxy.command('/status', 'GET');
} finally {
this.noSessionProxy.timeout = proxyTimeout;
}
currentStatus = res;
if (currentStatus.value && currentStatus.value.ios && currentStatus.value.ios.ip) {
this.agentUrl = currentStatus.value.ios.ip;
log.debug(`WebDriverAgent running on ip '${this.agentUrl}'`);
Expand Down