playwrightConnection.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.PlaywrightConnection = void 0;
  6. var _server = require("../server");
  7. var _browser = require("../server/browser");
  8. var _instrumentation = require("../server/instrumentation");
  9. var _socksProxy = require("../common/socksProxy");
  10. var _utils = require("../utils");
  11. var _android = require("../server/android/android");
  12. var _debugControllerDispatcher = require("../server/dispatchers/debugControllerDispatcher");
  13. var _debugLogger = require("../common/debugLogger");
  14. /**
  15. * Copyright (c) Microsoft Corporation.
  16. *
  17. * Licensed under the Apache License, Version 2.0 (the "License");
  18. * you may not use this file except in compliance with the License.
  19. * You may obtain a copy of the License at
  20. *
  21. * http://www.apache.org/licenses/LICENSE-2.0
  22. *
  23. * Unless required by applicable law or agreed to in writing, software
  24. * distributed under the License is distributed on an "AS IS" BASIS,
  25. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26. * See the License for the specific language governing permissions and
  27. * limitations under the License.
  28. */
  29. class PlaywrightConnection {
  30. constructor(lock, clientType, ws, options, preLaunched, id, onClose) {
  31. this._ws = void 0;
  32. this._onClose = void 0;
  33. this._dispatcherConnection = void 0;
  34. this._cleanups = [];
  35. this._id = void 0;
  36. this._disconnected = false;
  37. this._preLaunched = void 0;
  38. this._options = void 0;
  39. this._root = void 0;
  40. this._profileName = void 0;
  41. this._ws = ws;
  42. this._preLaunched = preLaunched;
  43. this._options = options;
  44. options.launchOptions = filterLaunchOptions(options.launchOptions);
  45. if (clientType === 'reuse-browser' || clientType === 'pre-launched-browser-or-android') (0, _utils.assert)(preLaunched.playwright);
  46. if (clientType === 'pre-launched-browser-or-android') (0, _utils.assert)(preLaunched.browser || preLaunched.androidDevice);
  47. this._onClose = onClose;
  48. this._id = id;
  49. this._profileName = `${new Date().toISOString()}-${clientType}`;
  50. this._dispatcherConnection = new _server.DispatcherConnection();
  51. this._dispatcherConnection.onmessage = async message => {
  52. await lock;
  53. if (ws.readyState !== ws.CLOSING) {
  54. const messageString = JSON.stringify(message);
  55. if (_debugLogger.debugLogger.isEnabled('server:channel')) _debugLogger.debugLogger.log('server:channel', `[${this._id}] ${(0, _utils.monotonicTime)() * 1000} SEND ► ${messageString}`);
  56. if (_debugLogger.debugLogger.isEnabled('server:metadata')) this.logServerMetadata(message, messageString, 'SEND');
  57. ws.send(messageString);
  58. }
  59. };
  60. ws.on('message', async message => {
  61. await lock;
  62. const messageString = Buffer.from(message).toString();
  63. const jsonMessage = JSON.parse(messageString);
  64. if (_debugLogger.debugLogger.isEnabled('server:channel')) _debugLogger.debugLogger.log('server:channel', `[${this._id}] ${(0, _utils.monotonicTime)() * 1000} ◀ RECV ${messageString}`);
  65. if (_debugLogger.debugLogger.isEnabled('server:metadata')) this.logServerMetadata(jsonMessage, messageString, 'RECV');
  66. this._dispatcherConnection.dispatch(jsonMessage);
  67. });
  68. ws.on('close', () => this._onDisconnect());
  69. ws.on('error', error => this._onDisconnect(error));
  70. if (clientType === 'controller') {
  71. this._root = this._initDebugControllerMode();
  72. return;
  73. }
  74. this._root = new _server.RootDispatcher(this._dispatcherConnection, async (scope, options) => {
  75. await (0, _utils.startProfiling)();
  76. if (clientType === 'reuse-browser') return await this._initReuseBrowsersMode(scope);
  77. if (clientType === 'pre-launched-browser-or-android') return this._preLaunched.browser ? await this._initPreLaunchedBrowserMode(scope) : await this._initPreLaunchedAndroidMode(scope);
  78. if (clientType === 'launch-browser') return await this._initLaunchBrowserMode(scope, options);
  79. throw new Error('Unsupported client type: ' + clientType);
  80. });
  81. }
  82. async _initLaunchBrowserMode(scope, options) {
  83. _debugLogger.debugLogger.log('server', `[${this._id}] engaged launch mode for "${this._options.browserName}"`);
  84. const playwright = (0, _server.createPlaywright)({
  85. sdkLanguage: options.sdkLanguage,
  86. isServer: true
  87. });
  88. const ownedSocksProxy = await this._createOwnedSocksProxy(playwright);
  89. const browser = await playwright[this._options.browserName].launch((0, _instrumentation.serverSideCallMetadata)(), this._options.launchOptions);
  90. this._cleanups.push(async () => {
  91. for (const browser of playwright.allBrowsers()) await browser.close({
  92. reason: 'Connection terminated'
  93. });
  94. });
  95. browser.on(_browser.Browser.Events.Disconnected, () => {
  96. // Underlying browser did close for some reason - force disconnect the client.
  97. this.close({
  98. code: 1001,
  99. reason: 'Browser closed'
  100. });
  101. });
  102. return new _server.PlaywrightDispatcher(scope, playwright, ownedSocksProxy, browser);
  103. }
  104. async _initPreLaunchedBrowserMode(scope) {
  105. var _this$_preLaunched$so;
  106. _debugLogger.debugLogger.log('server', `[${this._id}] engaged pre-launched (browser) mode`);
  107. const playwright = this._preLaunched.playwright;
  108. // Note: connected client owns the socks proxy and configures the pattern.
  109. (_this$_preLaunched$so = this._preLaunched.socksProxy) === null || _this$_preLaunched$so === void 0 ? void 0 : _this$_preLaunched$so.setPattern(this._options.socksProxyPattern);
  110. const browser = this._preLaunched.browser;
  111. browser.on(_browser.Browser.Events.Disconnected, () => {
  112. // Underlying browser did close for some reason - force disconnect the client.
  113. this.close({
  114. code: 1001,
  115. reason: 'Browser closed'
  116. });
  117. });
  118. const playwrightDispatcher = new _server.PlaywrightDispatcher(scope, playwright, this._preLaunched.socksProxy, browser);
  119. // In pre-launched mode, keep only the pre-launched browser.
  120. for (const b of playwright.allBrowsers()) {
  121. if (b !== browser) await b.close({
  122. reason: 'Connection terminated'
  123. });
  124. }
  125. this._cleanups.push(() => playwrightDispatcher.cleanup());
  126. return playwrightDispatcher;
  127. }
  128. async _initPreLaunchedAndroidMode(scope) {
  129. _debugLogger.debugLogger.log('server', `[${this._id}] engaged pre-launched (Android) mode`);
  130. const playwright = this._preLaunched.playwright;
  131. const androidDevice = this._preLaunched.androidDevice;
  132. androidDevice.on(_android.AndroidDevice.Events.Close, () => {
  133. // Underlying browser did close for some reason - force disconnect the client.
  134. this.close({
  135. code: 1001,
  136. reason: 'Android device disconnected'
  137. });
  138. });
  139. const playwrightDispatcher = new _server.PlaywrightDispatcher(scope, playwright, undefined, undefined, androidDevice);
  140. this._cleanups.push(() => playwrightDispatcher.cleanup());
  141. return playwrightDispatcher;
  142. }
  143. _initDebugControllerMode() {
  144. _debugLogger.debugLogger.log('server', `[${this._id}] engaged reuse controller mode`);
  145. const playwright = this._preLaunched.playwright;
  146. // Always create new instance based on the reused Playwright instance.
  147. return new _debugControllerDispatcher.DebugControllerDispatcher(this._dispatcherConnection, playwright.debugController);
  148. }
  149. async _initReuseBrowsersMode(scope) {
  150. // Note: reuse browser mode does not support socks proxy, because
  151. // clients come and go, while the browser stays the same.
  152. _debugLogger.debugLogger.log('server', `[${this._id}] engaged reuse browsers mode for ${this._options.browserName}`);
  153. const playwright = this._preLaunched.playwright;
  154. const requestedOptions = launchOptionsHash(this._options.launchOptions);
  155. let browser = playwright.allBrowsers().find(b => {
  156. if (b.options.name !== this._options.browserName) return false;
  157. const existingOptions = launchOptionsHash(b.options.originalLaunchOptions);
  158. return existingOptions === requestedOptions;
  159. });
  160. // Close remaining browsers of this type+channel. Keep different browser types for the speed.
  161. for (const b of playwright.allBrowsers()) {
  162. if (b === browser) continue;
  163. if (b.options.name === this._options.browserName && b.options.channel === this._options.launchOptions.channel) await b.close({
  164. reason: 'Connection terminated'
  165. });
  166. }
  167. if (!browser) {
  168. browser = await playwright[this._options.browserName || 'chromium'].launch((0, _instrumentation.serverSideCallMetadata)(), {
  169. ...this._options.launchOptions,
  170. headless: !!process.env.PW_DEBUG_CONTROLLER_HEADLESS
  171. });
  172. browser.on(_browser.Browser.Events.Disconnected, () => {
  173. // Underlying browser did close for some reason - force disconnect the client.
  174. this.close({
  175. code: 1001,
  176. reason: 'Browser closed'
  177. });
  178. });
  179. }
  180. this._cleanups.push(async () => {
  181. // Don't close the pages so that user could debug them,
  182. // but close all the empty browsers and contexts to clean up.
  183. for (const browser of playwright.allBrowsers()) {
  184. for (const context of browser.contexts()) {
  185. if (!context.pages().length) await context.close({
  186. reason: 'Connection terminated'
  187. });else await context.stopPendingOperations('Connection closed');
  188. }
  189. if (!browser.contexts()) await browser.close({
  190. reason: 'Connection terminated'
  191. });
  192. }
  193. });
  194. const playwrightDispatcher = new _server.PlaywrightDispatcher(scope, playwright, undefined, browser);
  195. return playwrightDispatcher;
  196. }
  197. async _createOwnedSocksProxy(playwright) {
  198. if (!this._options.socksProxyPattern) return;
  199. const socksProxy = new _socksProxy.SocksProxy();
  200. socksProxy.setPattern(this._options.socksProxyPattern);
  201. playwright.options.socksProxyPort = await socksProxy.listen(0);
  202. _debugLogger.debugLogger.log('server', `[${this._id}] started socks proxy on port ${playwright.options.socksProxyPort}`);
  203. this._cleanups.push(() => socksProxy.close());
  204. return socksProxy;
  205. }
  206. async _onDisconnect(error) {
  207. this._disconnected = true;
  208. _debugLogger.debugLogger.log('server', `[${this._id}] disconnected. error: ${error}`);
  209. this._root._dispose();
  210. _debugLogger.debugLogger.log('server', `[${this._id}] starting cleanup`);
  211. for (const cleanup of this._cleanups) await cleanup().catch(() => {});
  212. await (0, _utils.stopProfiling)(this._profileName);
  213. this._onClose();
  214. _debugLogger.debugLogger.log('server', `[${this._id}] finished cleanup`);
  215. }
  216. logServerMetadata(message, messageString, direction) {
  217. const serverLogMetadata = {
  218. wallTime: Date.now(),
  219. id: message.id,
  220. guid: message.guid,
  221. method: message.method,
  222. payloadSizeInBytes: Buffer.byteLength(messageString, 'utf-8')
  223. };
  224. _debugLogger.debugLogger.log('server:metadata', (direction === 'SEND' ? 'SEND ► ' : '◀ RECV ') + JSON.stringify(serverLogMetadata));
  225. }
  226. async close(reason) {
  227. if (this._disconnected) return;
  228. _debugLogger.debugLogger.log('server', `[${this._id}] force closing connection: ${(reason === null || reason === void 0 ? void 0 : reason.reason) || ''} (${(reason === null || reason === void 0 ? void 0 : reason.code) || 0})`);
  229. try {
  230. this._ws.close(reason === null || reason === void 0 ? void 0 : reason.code, reason === null || reason === void 0 ? void 0 : reason.reason);
  231. } catch (e) {}
  232. }
  233. }
  234. exports.PlaywrightConnection = PlaywrightConnection;
  235. function launchOptionsHash(options) {
  236. const copy = {
  237. ...options
  238. };
  239. for (const k of Object.keys(copy)) {
  240. const key = k;
  241. if (copy[key] === defaultLaunchOptions[key]) delete copy[key];
  242. }
  243. for (const key of optionsThatAllowBrowserReuse) delete copy[key];
  244. return JSON.stringify(copy);
  245. }
  246. function filterLaunchOptions(options) {
  247. return {
  248. channel: options.channel,
  249. args: options.args,
  250. ignoreAllDefaultArgs: options.ignoreAllDefaultArgs,
  251. ignoreDefaultArgs: options.ignoreDefaultArgs,
  252. timeout: options.timeout,
  253. headless: options.headless,
  254. proxy: options.proxy,
  255. chromiumSandbox: options.chromiumSandbox,
  256. firefoxUserPrefs: options.firefoxUserPrefs,
  257. slowMo: options.slowMo,
  258. executablePath: (0, _utils.isUnderTest)() ? options.executablePath : undefined
  259. };
  260. }
  261. const defaultLaunchOptions = {
  262. ignoreAllDefaultArgs: false,
  263. handleSIGINT: false,
  264. handleSIGTERM: false,
  265. handleSIGHUP: false,
  266. headless: true,
  267. devtools: false
  268. };
  269. const optionsThatAllowBrowserReuse = ['headless', 'tracesDir'];