playwrightServer.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.Semaphore = exports.PlaywrightServer = void 0;
  6. var _utilsBundle = require("../utilsBundle");
  7. var _playwright = require("../server/playwright");
  8. var _playwrightConnection = require("./playwrightConnection");
  9. var _manualPromise = require("../utils/manualPromise");
  10. var _debugLogger = require("../common/debugLogger");
  11. var _utils = require("../utils");
  12. var _transport = require("../server/transport");
  13. /**
  14. * Copyright (c) Microsoft Corporation.
  15. *
  16. * Licensed under the Apache License, Version 2.0 (the "License");
  17. * you may not use this file except in compliance with the License.
  18. * You may obtain a copy of the License at
  19. *
  20. * http://www.apache.org/licenses/LICENSE-2.0
  21. *
  22. * Unless required by applicable law or agreed to in writing, software
  23. * distributed under the License is distributed on an "AS IS" BASIS,
  24. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25. * See the License for the specific language governing permissions and
  26. * limitations under the License.
  27. */
  28. let lastConnectionId = 0;
  29. const kConnectionSymbol = Symbol('kConnection');
  30. class PlaywrightServer {
  31. constructor(options) {
  32. this._preLaunchedPlaywright = void 0;
  33. this._wsServer = void 0;
  34. this._server = void 0;
  35. this._options = void 0;
  36. this._options = options;
  37. if (options.preLaunchedBrowser) this._preLaunchedPlaywright = options.preLaunchedBrowser.attribution.playwright;
  38. if (options.preLaunchedAndroidDevice) this._preLaunchedPlaywright = options.preLaunchedAndroidDevice._android.attribution.playwright;
  39. }
  40. async listen(port = 0, hostname) {
  41. _debugLogger.debugLogger.log('server', `Server started at ${new Date()}`);
  42. const server = (0, _utils.createHttpServer)((request, response) => {
  43. if (request.method === 'GET' && request.url === '/json') {
  44. response.setHeader('Content-Type', 'application/json');
  45. response.end(JSON.stringify({
  46. wsEndpointPath: this._options.path
  47. }));
  48. return;
  49. }
  50. response.end('Running');
  51. });
  52. server.on('error', error => _debugLogger.debugLogger.log('server', String(error)));
  53. this._server = server;
  54. const wsEndpoint = await new Promise((resolve, reject) => {
  55. server.listen(port, hostname, () => {
  56. const address = server.address();
  57. if (!address) {
  58. reject(new Error('Could not bind server socket'));
  59. return;
  60. }
  61. const wsEndpoint = typeof address === 'string' ? `${address}${this._options.path}` : `ws://${hostname || 'localhost'}:${address.port}${this._options.path}`;
  62. resolve(wsEndpoint);
  63. }).on('error', reject);
  64. });
  65. _debugLogger.debugLogger.log('server', 'Listening at ' + wsEndpoint);
  66. this._wsServer = new _utilsBundle.wsServer({
  67. noServer: true,
  68. perMessageDeflate: _transport.perMessageDeflate
  69. });
  70. const browserSemaphore = new Semaphore(this._options.maxConnections);
  71. const controllerSemaphore = new Semaphore(1);
  72. const reuseBrowserSemaphore = new Semaphore(1);
  73. if (process.env.PWTEST_SERVER_WS_HEADERS) {
  74. this._wsServer.on('headers', (headers, request) => {
  75. headers.push(process.env.PWTEST_SERVER_WS_HEADERS);
  76. });
  77. }
  78. server.on('upgrade', (request, socket, head) => {
  79. var _this$_wsServer;
  80. const pathname = new URL('http://localhost' + request.url).pathname;
  81. if (pathname !== this._options.path) {
  82. socket.write(`HTTP/${request.httpVersion} 400 Bad Request\r\n\r\n`);
  83. socket.destroy();
  84. return;
  85. }
  86. const uaError = (0, _utils.userAgentVersionMatchesErrorMessage)(request.headers['user-agent'] || '');
  87. if (uaError) {
  88. socket.write(`HTTP/${request.httpVersion} 428 Precondition Required\r\n\r\n${uaError}`);
  89. socket.destroy();
  90. return;
  91. }
  92. (_this$_wsServer = this._wsServer) === null || _this$_wsServer === void 0 ? void 0 : _this$_wsServer.handleUpgrade(request, socket, head, ws => {
  93. var _this$_wsServer2;
  94. return (_this$_wsServer2 = this._wsServer) === null || _this$_wsServer2 === void 0 ? void 0 : _this$_wsServer2.emit('connection', ws, request);
  95. });
  96. });
  97. this._wsServer.on('connection', (ws, request) => {
  98. _debugLogger.debugLogger.log('server', 'Connected client ws.extension=' + ws.extensions);
  99. const url = new URL('http://localhost' + (request.url || ''));
  100. const browserHeader = request.headers['x-playwright-browser'];
  101. const browserName = url.searchParams.get('browser') || (Array.isArray(browserHeader) ? browserHeader[0] : browserHeader) || null;
  102. const proxyHeader = request.headers['x-playwright-proxy'];
  103. const proxyValue = url.searchParams.get('proxy') || (Array.isArray(proxyHeader) ? proxyHeader[0] : proxyHeader);
  104. const launchOptionsHeader = request.headers['x-playwright-launch-options'] || '';
  105. const launchOptionsHeaderValue = Array.isArray(launchOptionsHeader) ? launchOptionsHeader[0] : launchOptionsHeader;
  106. const launchOptionsParam = url.searchParams.get('launch-options');
  107. let launchOptions = {};
  108. try {
  109. launchOptions = JSON.parse(launchOptionsParam || launchOptionsHeaderValue);
  110. } catch (e) {}
  111. const id = String(++lastConnectionId);
  112. _debugLogger.debugLogger.log('server', `[${id}] serving connection: ${request.url}`);
  113. // Instantiate playwright for the extension modes.
  114. const isExtension = this._options.mode === 'extension';
  115. if (isExtension) {
  116. if (!this._preLaunchedPlaywright) this._preLaunchedPlaywright = (0, _playwright.createPlaywright)({
  117. sdkLanguage: 'javascript',
  118. isServer: true
  119. });
  120. }
  121. let clientType = 'launch-browser';
  122. let semaphore = browserSemaphore;
  123. if (isExtension && url.searchParams.has('debug-controller')) {
  124. clientType = 'controller';
  125. semaphore = controllerSemaphore;
  126. } else if (isExtension) {
  127. clientType = 'reuse-browser';
  128. semaphore = reuseBrowserSemaphore;
  129. } else if (this._options.mode === 'launchServer') {
  130. clientType = 'pre-launched-browser-or-android';
  131. semaphore = browserSemaphore;
  132. }
  133. const connection = new _playwrightConnection.PlaywrightConnection(semaphore.acquire(), clientType, ws, {
  134. socksProxyPattern: proxyValue,
  135. browserName,
  136. launchOptions
  137. }, {
  138. playwright: this._preLaunchedPlaywright,
  139. browser: this._options.preLaunchedBrowser,
  140. androidDevice: this._options.preLaunchedAndroidDevice,
  141. socksProxy: this._options.preLaunchedSocksProxy
  142. }, id, () => semaphore.release());
  143. ws[kConnectionSymbol] = connection;
  144. });
  145. return wsEndpoint;
  146. }
  147. async close() {
  148. const server = this._wsServer;
  149. if (!server) return;
  150. _debugLogger.debugLogger.log('server', 'closing websocket server');
  151. const waitForClose = new Promise(f => server.close(f));
  152. // First disconnect all remaining clients.
  153. await Promise.all(Array.from(server.clients).map(async ws => {
  154. const connection = ws[kConnectionSymbol];
  155. if (connection) await connection.close();
  156. try {
  157. ws.terminate();
  158. } catch (e) {}
  159. }));
  160. await waitForClose;
  161. _debugLogger.debugLogger.log('server', 'closing http server');
  162. if (this._server) await new Promise(f => this._server.close(f));
  163. this._wsServer = undefined;
  164. this._server = undefined;
  165. _debugLogger.debugLogger.log('server', 'closed server');
  166. _debugLogger.debugLogger.log('server', 'closing browsers');
  167. if (this._preLaunchedPlaywright) await Promise.all(this._preLaunchedPlaywright.allBrowsers().map(browser => browser.close({
  168. reason: 'Playwright Server stopped'
  169. })));
  170. _debugLogger.debugLogger.log('server', 'closed browsers');
  171. }
  172. }
  173. exports.PlaywrightServer = PlaywrightServer;
  174. class Semaphore {
  175. constructor(max) {
  176. this._max = void 0;
  177. this._acquired = 0;
  178. this._queue = [];
  179. this._max = max;
  180. }
  181. setMax(max) {
  182. this._max = max;
  183. }
  184. acquire() {
  185. const lock = new _manualPromise.ManualPromise();
  186. this._queue.push(lock);
  187. this._flush();
  188. return lock;
  189. }
  190. release() {
  191. --this._acquired;
  192. this._flush();
  193. }
  194. _flush() {
  195. while (this._acquired < this._max && this._queue.length) {
  196. ++this._acquired;
  197. this._queue.shift().resolve();
  198. }
  199. }
  200. }
  201. exports.Semaphore = Semaphore;