forked from AnWeber/httpyac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocketRequestClient.ts
228 lines (210 loc) · 6.96 KB
/
websocketRequestClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import * as models from '../../models';
import * as store from '../../store';
import * as utils from '../../utils';
import { isWebsocketRequest, WebsocketRequest } from './websocketRequest';
import { IncomingMessage } from 'http';
import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
import WebSocket, { ClientOptions } from 'ws';
const WEBSOCKET_CLOSE_NORMAL = 1000;
const WEBSOCKET_CLOSE_GOING_AWAY = 1001;
interface WebsocketSession extends models.UserSession {
client: WebSocket;
}
export class WebsocketRequestClient extends models.AbstractRequestClient<WebSocket | undefined> {
private closeOnFinish = true;
private _nativeClient: WebSocket | undefined;
private responseTemplate: Partial<models.HttpResponse> & { protocol: string } = {
protocol: 'WS',
};
constructor(private readonly request: models.Request, private readonly context: models.ProcessorContext) {
super();
}
get reportMessage(): string {
return `perform WebSocket Request (${this.request.url})`;
}
get supportsStreaming() {
return true;
}
get nativeClient(): WebSocket | undefined {
return this._nativeClient;
}
async connect(): Promise<void> {
if (isWebsocketRequest(this.request)) {
this._nativeClient = this.initWebsocket(this.request);
if (this.closeOnFinish) {
this.registerEvents(this._nativeClient);
await new Promise<void>(resolve => {
this._nativeClient?.on('open', () => {
resolve();
});
});
}
}
}
private initWebsocket(request: WebsocketRequest) {
const session: (models.UserSession & Partial<WebsocketSession>) | undefined = store.userSessionStore.getUserSession(
this.getWebsocketId(request)
);
if (session?.client) {
this.closeOnFinish = false;
return session.client;
}
const nativeClient = new WebSocket(this.request.url || '', this.getClientOptions(request));
this.setUserSession(request, nativeClient);
return nativeClient;
}
async send(body?: unknown): Promise<void> {
if (isWebsocketRequest(this.request)) {
const sendBody = utils.toBufferLike(body || this.request.body);
if (sendBody) {
this.nativeClient?.send(sendBody, err => {
if (err) {
this.onMessage('error', {
...this.responseTemplate,
statusCode: 400,
request: this.request,
body: utils.errorToString(err),
});
}
});
}
}
}
override disconnect(err?: Error): void {
if (this.closeOnFinish) {
this.removeWebsocketSession();
this.closeWebsocket(err);
}
}
private closeWebsocket(err?: Error) {
if (err) {
this._nativeClient?.close(WEBSOCKET_CLOSE_GOING_AWAY, err.message);
} else {
this._nativeClient?.close(WEBSOCKET_CLOSE_NORMAL, 'CLOSE_NORMAL');
}
this.onDisconnect();
}
private registerEvents(client: WebSocket) {
client.on('error', err => {
this.onMessage('error', {
...this.responseTemplate,
statusCode: 400,
request: this.request,
body: utils.toString(err),
});
});
client.on('message', message => {
this.onMessage('message', {
...this.responseTemplate,
statusCode: 0,
name: `${client.protocol} (${this.request.url})`,
message: utils.toString(message),
headers: {
date: new Date(),
},
request: this.request,
body: utils.toString(message),
rawBody: Buffer.isBuffer(message) ? message : undefined,
});
});
client.on('close', (statusCode, reason) => {
this.onMessage('message', {
...this.responseTemplate,
statusCode,
name: `${client.protocol} (${this.request.url})`,
message: utils.toString(reason),
headers: {
date: new Date(),
},
request: this.request,
body: utils.toString(reason),
rawBody: Buffer.isBuffer(reason) ? reason : undefined,
});
this.removeWebsocketSession();
});
const metaDataEvents = ['upgrade', 'unexpected-response', 'ping', 'pong', 'closing', 'close'];
for (const event of metaDataEvents) {
if (utils.isString(event)) {
client.on(event, (message: IncomingMessage) => {
this.onMetaData(event, {
...this.responseTemplate,
statusCode: message?.statusCode || 0,
statusMessage: message?.statusMessage,
headers: message?.headers,
httpVersion: message?.httpVersion,
message: message ? `${event}: ${utils.toString(message)}` : event,
body: {
event,
message,
date: new Date(),
},
});
});
}
}
}
private getClientOptions(request: WebsocketRequest): ClientOptions {
const { config } = this.context;
const configOptions: ClientOptions = {};
if (config?.request) {
configOptions.handshakeTimeout = utils.toNumber(config.request.timeout);
if (!utils.isUndefined(config.request.rejectUnauthorized)) {
configOptions.rejectUnauthorized = utils.toBoolean(config.request.rejectUnauthorized, true);
}
if (!utils.isUndefined(config.request.followRedirects)) {
configOptions.followRedirects = utils.toBoolean(config.request.followRedirects, true);
}
}
const metaDataOptions: Record<string, unknown> = {
headers: request.headers,
};
if (request.noRedirect) {
metaDataOptions.followRedirects = false;
}
if (request.noRejectUnauthorized) {
metaDataOptions.rejectUnauthorized = false;
}
if (request.proxy) {
this.initProxy(configOptions, request.proxy);
}
return Object.assign({}, config?.request, request.options, metaDataOptions);
}
private getWebsocketId(request: WebsocketRequest) {
return `ws_${request.url}`;
}
private setUserSession(request: WebsocketRequest, client: WebSocket) {
const session: models.UserSession & WebsocketSession = {
id: this.getWebsocketId(request),
description: `Client for ${request.url}`,
details: {
url: request.url,
},
title: `WS Client for ${request.url}`,
type: 'WS',
client,
delete: async () => {
this.closeWebsocket();
},
};
store.userSessionStore.setUserSession(session);
}
private removeWebsocketSession() {
if (isWebsocketRequest(this.request)) {
store.userSessionStore.removeUserSession(this.getWebsocketId(this.request));
}
}
private initProxy(options: ClientOptions, proxy: string | undefined) {
if (proxy) {
if (proxy.startsWith('socks://')) {
const socksProxy = new SocksProxyAgent(proxy);
options.agent = socksProxy;
} else if (proxy.startsWith('http://')) {
options.agent = new HttpProxyAgent(proxy);
} else {
options.agent = new HttpsProxyAgent(proxy);
}
}
}
}