2022-04-05 14:47:11 -07:00
|
|
|
/**
|
|
|
|
* Copyright (c) Microsoft Corporation.
|
|
|
|
*
|
|
|
|
* 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.
|
|
|
|
*/
|
|
|
|
|
2022-04-18 19:20:49 -08:00
|
|
|
import type { WebSocket } from '../utilsBundle';
|
2022-08-04 15:04:00 -07:00
|
|
|
import type { Playwright, DispatcherScope } from '../server';
|
2022-04-06 21:21:27 -08:00
|
|
|
import { createPlaywright, DispatcherConnection, Root, PlaywrightDispatcher } from '../server';
|
2022-04-05 14:47:11 -07:00
|
|
|
import { Browser } from '../server/browser';
|
|
|
|
import { serverSideCallMetadata } from '../server/instrumentation';
|
|
|
|
import { gracefullyCloseAll } from '../utils/processLauncher';
|
2022-04-07 13:36:13 -08:00
|
|
|
import { SocksProxy } from '../common/socksProxy';
|
2022-07-31 14:31:17 -07:00
|
|
|
import type { Mode } from './playwrightServer';
|
|
|
|
import { assert } from '../utils';
|
2022-08-03 17:32:29 -07:00
|
|
|
import type { LaunchOptions } from '../server/types';
|
2022-07-31 14:31:17 -07:00
|
|
|
|
|
|
|
type Options = {
|
|
|
|
enableSocksProxy: boolean,
|
2022-08-04 15:04:00 -07:00
|
|
|
browserName: string | null,
|
2022-08-03 17:32:29 -07:00
|
|
|
launchOptions: LaunchOptions,
|
2022-07-31 14:31:17 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
type PreLaunched = {
|
|
|
|
playwright: Playwright | null;
|
|
|
|
browser: Browser | null;
|
|
|
|
};
|
2022-04-05 14:47:11 -07:00
|
|
|
|
|
|
|
export class PlaywrightConnection {
|
|
|
|
private _ws: WebSocket;
|
|
|
|
private _onClose: () => void;
|
|
|
|
private _dispatcherConnection: DispatcherConnection;
|
|
|
|
private _cleanups: (() => Promise<void>)[] = [];
|
|
|
|
private _debugLog: (m: string) => void;
|
|
|
|
private _disconnected = false;
|
2022-07-31 14:31:17 -07:00
|
|
|
private _preLaunched: PreLaunched;
|
|
|
|
private _options: Options;
|
|
|
|
private _root: Root;
|
2022-04-05 14:47:11 -07:00
|
|
|
|
2022-08-03 19:37:06 -07:00
|
|
|
constructor(lock: Promise<void>, mode: Mode, ws: WebSocket, options: Options, preLaunched: PreLaunched, log: (m: string) => void, onClose: () => void) {
|
2022-04-05 14:47:11 -07:00
|
|
|
this._ws = ws;
|
2022-07-31 14:31:17 -07:00
|
|
|
this._preLaunched = preLaunched;
|
|
|
|
this._options = options;
|
|
|
|
if (mode === 'reuse-browser' || mode === 'use-pre-launched-browser')
|
|
|
|
assert(preLaunched.playwright);
|
|
|
|
if (mode === 'use-pre-launched-browser')
|
|
|
|
assert(preLaunched.browser);
|
2022-04-05 14:47:11 -07:00
|
|
|
this._onClose = onClose;
|
|
|
|
this._debugLog = log;
|
|
|
|
|
|
|
|
this._dispatcherConnection = new DispatcherConnection();
|
2022-08-03 19:37:06 -07:00
|
|
|
this._dispatcherConnection.onmessage = async message => {
|
|
|
|
await lock;
|
2022-04-05 14:47:11 -07:00
|
|
|
if (ws.readyState !== ws.CLOSING)
|
|
|
|
ws.send(JSON.stringify(message));
|
|
|
|
};
|
2022-08-03 19:37:06 -07:00
|
|
|
ws.on('message', async (message: string) => {
|
|
|
|
await lock;
|
2022-04-05 14:47:11 -07:00
|
|
|
this._dispatcherConnection.dispatch(JSON.parse(Buffer.from(message).toString()));
|
|
|
|
});
|
|
|
|
|
|
|
|
ws.on('close', () => this._onDisconnect());
|
|
|
|
ws.on('error', error => this._onDisconnect(error));
|
|
|
|
|
2022-07-31 14:31:17 -07:00
|
|
|
this._root = new Root(this._dispatcherConnection, async scope => {
|
|
|
|
if (mode === 'reuse-browser')
|
|
|
|
return await this._initReuseBrowsersMode(scope);
|
|
|
|
if (mode === 'use-pre-launched-browser')
|
|
|
|
return await this._initPreLaunchedBrowserMode(scope);
|
2022-08-04 15:04:00 -07:00
|
|
|
if (!options.browserName)
|
2022-07-31 14:31:17 -07:00
|
|
|
return await this._initPlaywrightConnectMode(scope);
|
|
|
|
return await this._initLaunchBrowserMode(scope);
|
2022-04-05 14:47:11 -07:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-07-31 14:31:17 -07:00
|
|
|
private async _initPlaywrightConnectMode(scope: DispatcherScope) {
|
2022-04-05 14:47:11 -07:00
|
|
|
this._debugLog(`engaged playwright.connect mode`);
|
|
|
|
const playwright = createPlaywright('javascript');
|
|
|
|
// Close all launched browsers on disconnect.
|
|
|
|
this._cleanups.push(() => gracefullyCloseAll());
|
|
|
|
|
2022-07-31 14:31:17 -07:00
|
|
|
const socksProxy = this._options.enableSocksProxy ? await this._enableSocksProxy(playwright) : undefined;
|
2022-04-05 14:47:11 -07:00
|
|
|
return new PlaywrightDispatcher(scope, playwright, socksProxy);
|
|
|
|
}
|
|
|
|
|
2022-07-31 14:31:17 -07:00
|
|
|
private async _initLaunchBrowserMode(scope: DispatcherScope) {
|
2022-08-04 15:04:00 -07:00
|
|
|
this._debugLog(`engaged launch mode for "${this._options.browserName}"`);
|
2022-04-05 14:47:11 -07:00
|
|
|
|
|
|
|
const playwright = createPlaywright('javascript');
|
2022-07-31 14:31:17 -07:00
|
|
|
const socksProxy = this._options.enableSocksProxy ? await this._enableSocksProxy(playwright) : undefined;
|
2022-08-04 15:04:00 -07:00
|
|
|
const browser = await playwright[this._options.browserName as 'chromium'].launch(serverSideCallMetadata(), this._options.launchOptions);
|
2022-04-05 14:47:11 -07:00
|
|
|
|
|
|
|
// Close the browser on disconnect.
|
|
|
|
// TODO: it is technically possible to launch more browsers over protocol.
|
|
|
|
this._cleanups.push(() => browser.close());
|
|
|
|
browser.on(Browser.Events.Disconnected, () => {
|
|
|
|
// Underlying browser did close for some reason - force disconnect the client.
|
|
|
|
this.close({ code: 1001, reason: 'Browser closed' });
|
|
|
|
});
|
|
|
|
|
|
|
|
return new PlaywrightDispatcher(scope, playwright, socksProxy, browser);
|
|
|
|
}
|
|
|
|
|
2022-07-31 14:31:17 -07:00
|
|
|
private async _initPreLaunchedBrowserMode(scope: DispatcherScope) {
|
2022-04-05 14:47:11 -07:00
|
|
|
this._debugLog(`engaged pre-launched mode`);
|
2022-07-31 14:31:17 -07:00
|
|
|
const playwright = this._preLaunched.playwright!;
|
|
|
|
const browser = this._preLaunched.browser!;
|
2022-04-05 14:47:11 -07:00
|
|
|
browser.on(Browser.Events.Disconnected, () => {
|
|
|
|
// Underlying browser did close for some reason - force disconnect the client.
|
|
|
|
this.close({ code: 1001, reason: 'Browser closed' });
|
|
|
|
});
|
|
|
|
const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, undefined, browser);
|
|
|
|
// In pre-launched mode, keep the browser and just cleanup new contexts.
|
|
|
|
// TODO: it is technically possible to launch more browsers over protocol.
|
|
|
|
this._cleanups.push(() => playwrightDispatcher.cleanup());
|
|
|
|
return playwrightDispatcher;
|
|
|
|
}
|
|
|
|
|
2022-07-31 14:31:17 -07:00
|
|
|
private async _initReuseBrowsersMode(scope: DispatcherScope) {
|
2022-08-04 15:04:00 -07:00
|
|
|
this._debugLog(`engaged reuse browsers mode for ${this._options.browserName}`);
|
2022-07-31 14:31:17 -07:00
|
|
|
const playwright = this._preLaunched.playwright!;
|
2022-08-03 17:32:29 -07:00
|
|
|
const requestedOptions = launchOptionsHash(this._options.launchOptions);
|
|
|
|
let browser = playwright.allBrowsers().find(b => {
|
2022-08-04 15:04:00 -07:00
|
|
|
if (b.options.name !== this._options.browserName)
|
|
|
|
return false;
|
2022-08-03 17:32:29 -07:00
|
|
|
const existingOptions = launchOptionsHash(b.options.originalLaunchOptions);
|
|
|
|
return existingOptions === requestedOptions;
|
|
|
|
});
|
2022-08-04 15:04:00 -07:00
|
|
|
|
|
|
|
// Close remaining browsers of this type+channel. Keep different browser types for the speed.
|
|
|
|
for (const b of playwright.allBrowsers()) {
|
|
|
|
if (b === browser)
|
|
|
|
continue;
|
|
|
|
if (b.options.name === this._options.browserName && b.options.channel === this._options.launchOptions.channel)
|
|
|
|
await b.close();
|
|
|
|
}
|
2022-07-31 14:31:17 -07:00
|
|
|
|
|
|
|
if (!browser) {
|
2022-08-04 15:04:00 -07:00
|
|
|
browser = await playwright[this._options.browserName as 'chromium'].launch(serverSideCallMetadata(), {
|
2022-08-03 17:32:29 -07:00
|
|
|
...this._options.launchOptions,
|
2022-07-31 14:31:17 -07:00
|
|
|
headless: false,
|
|
|
|
});
|
|
|
|
browser.on(Browser.Events.Disconnected, () => {
|
|
|
|
// Underlying browser did close for some reason - force disconnect the client.
|
|
|
|
this.close({ code: 1001, reason: 'Browser closed' });
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, undefined, browser);
|
|
|
|
return playwrightDispatcher;
|
|
|
|
}
|
|
|
|
|
2022-04-05 14:47:11 -07:00
|
|
|
private async _enableSocksProxy(playwright: Playwright) {
|
|
|
|
const socksProxy = new SocksProxy();
|
|
|
|
playwright.options.socksProxyPort = await socksProxy.listen(0);
|
|
|
|
this._debugLog(`started socks proxy on port ${playwright.options.socksProxyPort}`);
|
|
|
|
this._cleanups.push(() => socksProxy.close());
|
|
|
|
return socksProxy;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _onDisconnect(error?: Error) {
|
|
|
|
this._disconnected = true;
|
|
|
|
this._debugLog(`disconnected. error: ${error}`);
|
2022-07-31 14:31:17 -07:00
|
|
|
this._root._dispose();
|
2022-04-05 14:47:11 -07:00
|
|
|
this._debugLog(`starting cleanup`);
|
|
|
|
for (const cleanup of this._cleanups)
|
|
|
|
await cleanup().catch(() => {});
|
|
|
|
this._onClose();
|
|
|
|
this._debugLog(`finished cleanup`);
|
|
|
|
}
|
|
|
|
|
|
|
|
async close(reason?: { code: number, reason: string }) {
|
|
|
|
if (this._disconnected)
|
|
|
|
return;
|
|
|
|
this._debugLog(`force closing connection: ${reason?.reason || ''} (${reason?.code || 0})`);
|
|
|
|
try {
|
|
|
|
this._ws.close(reason?.code, reason?.reason);
|
|
|
|
} catch (e) {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-08-03 17:32:29 -07:00
|
|
|
|
|
|
|
function launchOptionsHash(options: LaunchOptions) {
|
|
|
|
const copy = { ...options };
|
|
|
|
for (const k of Object.keys(copy)) {
|
|
|
|
const key = k as keyof LaunchOptions;
|
|
|
|
if (copy[key] === defaultLaunchOptions[key])
|
|
|
|
delete copy[key];
|
|
|
|
}
|
|
|
|
for (const key of optionsThatAllowBrowserReuse)
|
|
|
|
delete copy[key];
|
|
|
|
return JSON.stringify(copy);
|
|
|
|
}
|
|
|
|
|
|
|
|
const defaultLaunchOptions: LaunchOptions = {
|
|
|
|
ignoreAllDefaultArgs: false,
|
|
|
|
handleSIGINT: false,
|
|
|
|
handleSIGTERM: false,
|
|
|
|
handleSIGHUP: false,
|
|
|
|
headless: true,
|
|
|
|
devtools: false,
|
|
|
|
};
|
|
|
|
|
|
|
|
const optionsThatAllowBrowserReuse: (keyof LaunchOptions)[] = [
|
|
|
|
'headless',
|
|
|
|
];
|