2019-11-18 18:18:28 -08:00
|
|
|
/**
|
|
|
|
* Copyright 2018 Google Inc. All rights reserved.
|
|
|
|
* Modifications 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 { ws } from '../utilsBundle';
|
|
|
|
import type { WebSocket } from '../utilsBundle';
|
2022-09-29 13:04:19 -08:00
|
|
|
import type { ClientRequest, IncomingMessage } from 'http';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { Progress } from './progress';
|
2022-04-07 12:55:44 -08:00
|
|
|
import { makeWaitForNextTask } from '../utils';
|
2023-02-22 17:09:56 +01:00
|
|
|
import { httpHappyEyeballsAgent, httpsHappyEyeballsAgent } from '../utils/happy-eyeballs';
|
2023-03-31 08:57:07 -07:00
|
|
|
import type { HeadersArray } from './types';
|
2020-04-01 14:42:47 -07:00
|
|
|
|
2023-08-25 16:13:46 -07:00
|
|
|
export const perMessageDeflate = {
|
|
|
|
zlibDeflateOptions: {
|
|
|
|
level: 3,
|
|
|
|
},
|
|
|
|
zlibInflateOptions: {
|
|
|
|
chunkSize: 10 * 1024
|
|
|
|
},
|
|
|
|
threshold: 10 * 1024,
|
|
|
|
};
|
|
|
|
|
2020-03-27 15:18:34 -07:00
|
|
|
export type ProtocolRequest = {
|
|
|
|
id: number;
|
2020-03-26 23:30:55 -07:00
|
|
|
method: string;
|
2020-03-27 15:18:34 -07:00
|
|
|
params: any;
|
|
|
|
sessionId?: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type ProtocolResponse = {
|
|
|
|
id?: number;
|
|
|
|
method?: string;
|
2020-03-26 23:30:55 -07:00
|
|
|
sessionId?: string;
|
2022-05-04 10:00:02 -07:00
|
|
|
error?: { message: string; data: any; code?: number };
|
2020-03-27 15:18:34 -07:00
|
|
|
params?: any;
|
2020-03-26 23:30:55 -07:00
|
|
|
result?: any;
|
|
|
|
pageProxyId?: string;
|
2020-06-10 13:36:45 -07:00
|
|
|
browserContextId?: string;
|
2020-03-26 23:30:55 -07:00
|
|
|
};
|
|
|
|
|
2019-12-12 21:30:49 -08:00
|
|
|
export interface ConnectionTransport {
|
2020-03-27 15:18:34 -07:00
|
|
|
send(s: ProtocolRequest): void;
|
2020-01-22 17:42:10 -08:00
|
|
|
close(): void; // Note: calling close is expected to issue onclose at some point.
|
2020-03-27 15:18:34 -07:00
|
|
|
onmessage?: (message: ProtocolResponse) => void,
|
2019-12-12 21:30:49 -08:00
|
|
|
onclose?: () => void,
|
|
|
|
}
|
|
|
|
|
2020-04-01 14:42:47 -07:00
|
|
|
export class WebSocketTransport implements ConnectionTransport {
|
2020-05-21 09:43:10 -07:00
|
|
|
private _ws: WebSocket;
|
2022-11-03 13:47:51 -07:00
|
|
|
private _progress?: Progress;
|
2023-01-11 12:27:27 -08:00
|
|
|
private _logUrl: string;
|
2020-04-01 14:42:47 -07:00
|
|
|
|
|
|
|
onmessage?: (message: ProtocolResponse) => void;
|
|
|
|
onclose?: () => void;
|
2021-02-15 08:32:13 -08:00
|
|
|
readonly wsEndpoint: string;
|
2023-03-31 08:57:07 -07:00
|
|
|
readonly headers: HeadersArray = [];
|
2020-04-01 14:42:47 -07:00
|
|
|
|
2023-05-16 16:46:02 -07:00
|
|
|
static async connect(progress: (Progress|undefined), url: string, headers?: { [key: string]: string; }, followRedirects?: boolean, debugLogHeader?: string): Promise<WebSocketTransport> {
|
2023-07-27 19:03:14 -07:00
|
|
|
return await WebSocketTransport._connect(progress, url, headers || {}, { follow: !!followRedirects, hadRedirects: false }, debugLogHeader);
|
|
|
|
}
|
|
|
|
|
|
|
|
static async _connect(progress: (Progress|undefined), url: string, headers: { [key: string]: string; }, redirect: { follow: boolean, hadRedirects: boolean }, debugLogHeader?: string): Promise<WebSocketTransport> {
|
2023-01-11 12:27:27 -08:00
|
|
|
const logUrl = stripQueryParams(url);
|
|
|
|
progress?.log(`<ws connecting> ${logUrl}`);
|
2023-07-27 19:03:14 -07:00
|
|
|
const transport = new WebSocketTransport(progress, url, logUrl, headers, redirect.follow && redirect.hadRedirects, debugLogHeader);
|
2020-06-04 16:43:48 -07:00
|
|
|
let success = false;
|
2022-11-03 13:47:51 -07:00
|
|
|
progress?.cleanupWhenAborted(async () => {
|
2020-06-04 16:43:48 -07:00
|
|
|
if (!success)
|
2021-02-08 17:33:01 -08:00
|
|
|
await transport.closeAndWait().catch(e => null);
|
2020-06-04 16:43:48 -07:00
|
|
|
});
|
2023-07-27 19:03:14 -07:00
|
|
|
const result = await new Promise<{ transport?: WebSocketTransport, redirect?: IncomingMessage }>((fulfill, reject) => {
|
2022-09-29 13:04:19 -08:00
|
|
|
transport._ws.on('open', async () => {
|
2023-01-11 12:27:27 -08:00
|
|
|
progress?.log(`<ws connected> ${logUrl}`);
|
2023-07-27 19:03:14 -07:00
|
|
|
fulfill({ transport });
|
2020-05-11 13:49:57 -07:00
|
|
|
});
|
2022-09-29 13:04:19 -08:00
|
|
|
transport._ws.on('error', event => {
|
2023-01-11 12:27:27 -08:00
|
|
|
progress?.log(`<ws connect error> ${logUrl} ${event.message}`);
|
2020-05-18 19:00:38 -07:00
|
|
|
reject(new Error('WebSocket error: ' + event.message));
|
2020-05-21 09:43:10 -07:00
|
|
|
transport._ws.close();
|
2020-05-18 19:00:38 -07:00
|
|
|
});
|
2022-09-29 13:04:19 -08:00
|
|
|
transport._ws.on('unexpected-response', (request: ClientRequest, response: IncomingMessage) => {
|
2023-07-27 19:03:14 -07:00
|
|
|
if (redirect.follow && !redirect.hadRedirects && (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 307 || response.statusCode === 308)) {
|
|
|
|
fulfill({ redirect: response });
|
|
|
|
transport._ws.close();
|
|
|
|
return;
|
|
|
|
}
|
2023-05-16 16:46:02 -07:00
|
|
|
for (let i = 0; i < response.rawHeaders.length; i += 2) {
|
|
|
|
if (debugLogHeader && response.rawHeaders[i] === debugLogHeader)
|
|
|
|
progress?.log(response.rawHeaders[i + 1]);
|
|
|
|
}
|
2022-09-29 13:04:19 -08:00
|
|
|
const chunks: Buffer[] = [];
|
2023-01-11 12:27:27 -08:00
|
|
|
const errorPrefix = `${logUrl} ${response.statusCode} ${response.statusMessage}`;
|
2022-09-29 13:04:19 -08:00
|
|
|
response.on('data', chunk => chunks.push(chunk));
|
|
|
|
response.on('close', () => {
|
|
|
|
const error = chunks.length ? `${errorPrefix}\n${Buffer.concat(chunks)}` : errorPrefix;
|
2022-11-03 13:47:51 -07:00
|
|
|
progress?.log(`<ws unexpected response> ${error}`);
|
2022-09-29 13:04:19 -08:00
|
|
|
reject(new Error('WebSocket error: ' + error));
|
|
|
|
transport._ws.close();
|
|
|
|
});
|
|
|
|
});
|
2020-04-01 14:42:47 -07:00
|
|
|
});
|
2023-07-27 19:03:14 -07:00
|
|
|
|
|
|
|
if (result.redirect) {
|
|
|
|
// Strip access key headers from the redirected request.
|
|
|
|
const newHeaders = Object.fromEntries(Object.entries(headers || {}).filter(([name]) => !name.includes('access-key')));
|
|
|
|
return WebSocketTransport._connect(progress, result.redirect.headers.location!, newHeaders, { follow: true, hadRedirects: true }, debugLogHeader);
|
|
|
|
}
|
|
|
|
|
2020-06-04 16:43:48 -07:00
|
|
|
success = true;
|
|
|
|
return transport;
|
2020-04-01 14:42:47 -07:00
|
|
|
}
|
|
|
|
|
2023-05-16 16:46:02 -07:00
|
|
|
constructor(progress: Progress|undefined, url: string, logUrl: string, headers?: { [key: string]: string; }, followRedirects?: boolean, debugLogHeader?: string) {
|
2021-02-15 08:32:13 -08:00
|
|
|
this.wsEndpoint = url;
|
2023-01-11 12:27:27 -08:00
|
|
|
this._logUrl = logUrl;
|
2022-04-18 19:20:49 -08:00
|
|
|
this._ws = new ws(url, [], {
|
2020-05-21 09:43:10 -07:00
|
|
|
maxPayload: 256 * 1024 * 1024, // 256Mb,
|
2022-03-29 15:03:43 -07:00
|
|
|
// Prevent internal http client error when passing negative timeout.
|
2022-11-03 13:47:51 -07:00
|
|
|
handshakeTimeout: Math.max(progress?.timeUntilDeadline() ?? 30_000, 1),
|
2022-02-17 20:48:14 -08:00
|
|
|
headers,
|
|
|
|
followRedirects,
|
2023-08-25 16:13:46 -07:00
|
|
|
agent: (/^(https|wss):\/\//.test(url)) ? httpsHappyEyeballsAgent : httpHappyEyeballsAgent,
|
|
|
|
perMessageDeflate,
|
2020-04-01 14:42:47 -07:00
|
|
|
});
|
2023-05-16 16:46:02 -07:00
|
|
|
this._ws.on('upgrade', response => {
|
|
|
|
for (let i = 0; i < response.rawHeaders.length; i += 2) {
|
|
|
|
this.headers.push({ name: response.rawHeaders[i], value: response.rawHeaders[i + 1] });
|
|
|
|
if (debugLogHeader && response.rawHeaders[i] === debugLogHeader)
|
|
|
|
progress?.log(response.rawHeaders[i + 1]);
|
|
|
|
}
|
2023-03-31 08:57:07 -07:00
|
|
|
});
|
2020-05-29 14:39:34 -07:00
|
|
|
this._progress = progress;
|
2020-04-01 14:42:47 -07:00
|
|
|
// The 'ws' module in node sometimes sends us multiple messages in a single task.
|
|
|
|
// In Web, all IO callbacks (e.g. WebSocket callbacks)
|
|
|
|
// are dispatched into separate tasks, so there's no need
|
|
|
|
// to do anything extra.
|
2020-08-22 07:07:13 -07:00
|
|
|
const messageWrap: (cb: () => void) => void = makeWaitForNextTask();
|
2020-04-01 14:42:47 -07:00
|
|
|
|
|
|
|
this._ws.addEventListener('message', event => {
|
|
|
|
messageWrap(() => {
|
2023-06-19 20:12:02 +02:00
|
|
|
const eventData = event.data as string;
|
|
|
|
let parsedJson;
|
|
|
|
try {
|
|
|
|
parsedJson = JSON.parse(eventData);
|
|
|
|
} catch (e) {
|
|
|
|
this._progress?.log(`<closing ws> Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`);
|
|
|
|
this._ws.close();
|
|
|
|
return;
|
|
|
|
}
|
2021-04-23 14:52:27 -07:00
|
|
|
try {
|
|
|
|
if (this.onmessage)
|
2023-06-19 20:12:02 +02:00
|
|
|
this.onmessage.call(null, parsedJson);
|
2021-04-23 14:52:27 -07:00
|
|
|
} catch (e) {
|
2023-06-19 20:12:02 +02:00
|
|
|
this._progress?.log(`<closing ws> Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`);
|
2021-04-23 14:52:27 -07:00
|
|
|
this._ws.close();
|
|
|
|
}
|
2020-04-01 14:42:47 -07:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
this._ws.addEventListener('close', event => {
|
2023-01-11 12:27:27 -08:00
|
|
|
this._progress?.log(`<ws disconnected> ${logUrl} code=${event.code} reason=${event.reason}`);
|
2020-04-01 14:42:47 -07:00
|
|
|
if (this.onclose)
|
|
|
|
this.onclose.call(null);
|
|
|
|
});
|
2020-10-27 11:09:41 -07:00
|
|
|
// Prevent Error: read ECONNRESET.
|
2023-01-11 12:27:27 -08:00
|
|
|
this._ws.addEventListener('error', error => this._progress?.log(`<ws error> ${logUrl} ${error.type} ${error.message}`));
|
2020-04-01 14:42:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
send(message: ProtocolRequest) {
|
|
|
|
this._ws.send(JSON.stringify(message));
|
|
|
|
}
|
|
|
|
|
|
|
|
close() {
|
2023-01-11 12:27:27 -08:00
|
|
|
this._progress?.log(`<ws disconnecting> ${this._logUrl}`);
|
2020-04-01 14:42:47 -07:00
|
|
|
this._ws.close();
|
|
|
|
}
|
2020-05-29 14:39:34 -07:00
|
|
|
|
|
|
|
async closeAndWait() {
|
2022-04-18 19:20:49 -08:00
|
|
|
if (this._ws.readyState === ws.CLOSED)
|
2022-02-17 20:48:14 -08:00
|
|
|
return;
|
2021-02-10 14:00:02 -08:00
|
|
|
const promise = new Promise(f => this._ws.once('close', f));
|
2020-05-29 14:39:34 -07:00
|
|
|
this.close();
|
2021-02-10 14:00:02 -08:00
|
|
|
await promise; // Make sure to await the actual disconnect.
|
2020-05-29 14:39:34 -07:00
|
|
|
}
|
2020-04-01 14:42:47 -07:00
|
|
|
}
|
2023-01-11 12:27:27 -08:00
|
|
|
|
|
|
|
function stripQueryParams(url: string): string {
|
|
|
|
try {
|
|
|
|
const u = new URL(url);
|
|
|
|
u.search = '';
|
|
|
|
u.hash = '';
|
|
|
|
return u.toString();
|
|
|
|
} catch {
|
|
|
|
return url;
|
|
|
|
}
|
|
|
|
}
|