-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathwebsocket-client.ts
405 lines (338 loc) · 12.8 KB
/
websocket-client.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { EventEmitter } from 'events';
import { RestClient } from './rest-client';
import { DefaultLogger } from './logger';
import { WSClientConfigurableOptions, getWsUrl, WebsocketClientOptions, parseRawWsMessage } from './util/requestUtils';
import WebSocket from 'isomorphic-ws';
import WsStore from './util/WsStore';
import { getWsAuthMessage, isWsPong } from './util/wsMessages';
import { signMessage, signWsAuthenticate } from './util/node-support';
import type { WsChannel, WsEvent, WsTopic } from './types/websockets';
const loggerCategory = { category: 'ftx-ws' };
const READY_STATE_INITIAL = 0;
const READY_STATE_CONNECTING = 1;
const READY_STATE_CONNECTED = 2;
const READY_STATE_CLOSING = 3;
const READY_STATE_RECONNECTING = 4;
export enum WsConnectionState {
READY_STATE_INITIAL,
READY_STATE_CONNECTING,
READY_STATE_CONNECTED,
READY_STATE_CLOSING,
READY_STATE_RECONNECTING
};
export const wsKeyGeneral = 'ftx';
export declare interface WebsocketClient {
on(event: 'open' | 'reconnected', listener: ({ wsKey: string, event: any }) => void): this;
on(event: 'response' | 'error', listener: (response: any) => void): this;
on(event: 'update', listener: (response: WsEvent | any) => void): this;
on(event: 'reconnect' | 'close', listener: () => void): this;
};
export class WebsocketClient extends EventEmitter {
private logger: typeof DefaultLogger;
private restClient: RestClient;
private options: WebsocketClientOptions;
public wsStore: WsStore;
constructor(options: WSClientConfigurableOptions, logger?: typeof DefaultLogger) {
super();
this.logger = logger || DefaultLogger;
this.wsStore = new WsStore(this.logger);
this.options = {
pongTimeout: 7500,
pingInterval: 10000,
reconnectTimeout: 500,
reconnectOnClose: true,
...options
};
if (options.domain != this.options.restOptions?.domain) {
this.options.restOptions = {
...this.options.restOptions,
domain: options.domain
};
}
this.restClient = new RestClient(undefined, undefined, this.options.restOptions, this.options.requestOptions);
}
public isLivenet(): boolean {
return true;
}
/**
* Add topic/topics to WS subscription list
*/
public subscribe(wsTopics: WsTopic[] | WsTopic | WsChannel[] | WsChannel) {
const mixedTopics = Array.isArray(wsTopics) ? wsTopics : [wsTopics];
const topics = mixedTopics.map(topic => {
return typeof topic === 'string' ? { channel: topic } : topic;
});
topics.forEach(topic => this.wsStore.addTopic(
this.getWsKeyForTopic(topic),
topic
));
// attempt to send subscription topic per websocket
this.wsStore.getKeys().forEach(wsKey => {
// if connected, send subscription request
if (this.wsStore.isConnectionState(wsKey, READY_STATE_CONNECTED)) {
return this.requestSubscribeTopics(wsKey, topics);
}
// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
if (
!this.wsStore.isConnectionState(wsKey, READY_STATE_CONNECTING) &&
!this.wsStore.isConnectionState(wsKey, READY_STATE_RECONNECTING)
) {
return this.connect(wsKey);
}
});
}
/**
* Remove topic/topics from WS subscription list
*/
public unsubscribe(wsTopics: WsTopic[] | WsTopic | WsChannel[] | WsChannel) {
const mixedTopics = Array.isArray(wsTopics) ? wsTopics : [wsTopics];
const topics = mixedTopics.map(topic => {
return typeof topic === 'string' ? { channel: topic } : topic;
});
topics.forEach(topic => this.wsStore.deleteTopic(
this.getWsKeyForTopic(topic),
topic
));
this.wsStore.getKeys().forEach(wsKey => {
// unsubscribe request only necessary if active connection exists
if (this.wsStore.isConnectionState(wsKey, READY_STATE_CONNECTED)) {
this.requestUnsubscribeTopics(wsKey, topics)
}
});
}
public close(wsKey: string) {
this.logger.info('Closing connection', { ...loggerCategory, wsKey });
this.setWsState(wsKey, READY_STATE_CLOSING);
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);
this.getWs(wsKey)?.close();
}
/**
* Request connection of all dependent websockets, instead of waiting for automatic connection by library
*/
public connectAll(): Promise<WebSocket | undefined>[] | undefined {
return [this.connect(wsKeyGeneral)];
}
private async connect(wsKey: string): Promise<WebSocket | undefined> {
try {
if (this.wsStore.isWsOpen(wsKey)) {
this.logger.error('Refused to connect to ws with existing active connection', { ...loggerCategory, wsKey })
return this.wsStore.getWs(wsKey);
}
if (this.wsStore.isConnectionState(wsKey, READY_STATE_CONNECTING)) {
this.logger.error('Refused to connect to ws, connection attempt already active', { ...loggerCategory, wsKey })
return;
}
if (
!this.wsStore.getConnectionState(wsKey) ||
this.wsStore.isConnectionState(wsKey, READY_STATE_INITIAL)
) {
this.setWsState(wsKey, READY_STATE_CONNECTING);
}
const url = getWsUrl(this.options);
const ws = this.connectToWsUrl(url, wsKey);
return this.wsStore.setWs(wsKey, ws);
} catch (err) {
this.parseWsError('Connection failed', err, wsKey);
this.reconnectWithDelay(wsKey, this.options.reconnectTimeout!);
this.emit('error', { error: err, wsKey, type: 'CONNECTION_FAILED' });
}
}
private async requestTryAuthenticate(wsKey: string) {
const { key, secret, subAccountName } = this.options;
if (!key || !secret) {
this.logger.debug(`Connection "${wsKey}" will remain unauthenticated due to missing key/secret`);
return;
}
const timestamp = new Date().getTime();
const authMsg = getWsAuthMessage(
key,
await signWsAuthenticate(timestamp, secret),
timestamp,
subAccountName,
);
this.tryWsSend(wsKey, JSON.stringify(authMsg));
}
private parseWsError(context: string, error, wsKey: string) {
const logContext = { ...loggerCategory, wsKey, error };
if (!error.message) {
this.logger.error(`${context} due to unexpected error: `, logContext);
return;
}
switch (error.message) {
case 'Unexpected server response: 401':
this.logger.error(`${context} due to 401 authorization failure.`, logContext);
break;
default:
this.logger.error(`${context} due to unexpected response error: ${error?.msg || error?.message || error}`, logContext);
break;
}
}
/**
* Return params required to make authorized request
*/
private async getAuthParams(wsKey: string): Promise<string> {
const { key, secret } = this.options;
if (key && secret) {
this.logger.debug('Getting auth\'d request params', { ...loggerCategory, wsKey });
const timeOffset = await this.restClient.getTimeOffset();
const params: any = {
api_key: this.options.key,
expires: (Date.now() + timeOffset + 5000)
};
params.signature = signMessage('GET/realtime' + params.expires, secret);
return params;
} else if (!key || !secret) {
this.logger.warning('Connot authenticate websocket, either api or private keys missing.', { ...loggerCategory, wsKey });
} else {
this.logger.debug('Starting public only websocket client.', { ...loggerCategory, wsKey });
}
return '';
}
private reconnectWithDelay(wsKey: string, connectionDelayMs: number) {
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);
if (this.wsStore.getConnectionState(wsKey) !== READY_STATE_CONNECTING) {
this.setWsState(wsKey, READY_STATE_RECONNECTING);
}
setTimeout(() => {
this.logger.info('Reconnecting to websocket', { ...loggerCategory, wsKey });
this.connect(wsKey);
}, connectionDelayMs);
}
private ping(wsKey: string) {
this.clearPongTimer(wsKey);
this.logger.silly('Sending ping', { ...loggerCategory, wsKey });
this.tryWsSend(wsKey, JSON.stringify({ op: 'ping' }));
this.wsStore.get(wsKey, true)!.activePongTimer = setTimeout(() => {
this.logger.info('Pong timeout - clearing timers & closing socket to reconnect', { ...loggerCategory, wsKey });
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);
this.getWs(wsKey)?.close();
}, this.options.pongTimeout);
}
// Send a ping at intervals
private clearPingTimer(wsKey: string) {
const wsState = this.wsStore.get(wsKey);
if (wsState?.activePingTimer) {
clearInterval(wsState.activePingTimer);
wsState.activePingTimer = undefined;
}
}
// Expect a pong within a time limit
private clearPongTimer(wsKey: string) {
const wsState = this.wsStore.get(wsKey);
if (wsState?.activePongTimer) {
clearTimeout(wsState.activePongTimer);
wsState.activePongTimer = undefined;
}
}
/**
* Send WS message to subscribe to topics.
*/
private requestSubscribeTopics(wsKey: string, topics: WsTopic[]) {
topics.forEach(topic => {
const wsMessage = JSON.stringify({
op: 'subscribe',
...topic
});
this.tryWsSend(wsKey, wsMessage);
});
}
/**
* Send WS message to unsubscribe from topics.
*/
private requestUnsubscribeTopics(wsKey: string, topics: WsTopic[]) {
topics.forEach(topic => {
const wsMessage = JSON.stringify({
op: 'unsubscribe',
...topic
});
this.tryWsSend(wsKey, wsMessage);
});
}
private tryWsSend(wsKey: string, wsMessage: string) {
try {
this.logger.silly(`Sending upstream ws message: `, { ...loggerCategory, wsMessage, wsKey });
if (!wsKey) {
throw new Error('Cannot send message due to no known websocket for this wsKey');
}
this.getWs(wsKey)?.send(wsMessage);
} catch (e) {
this.logger.error(`Failed to send WS message`, { ...loggerCategory, wsMessage, wsKey, exception: e });
}
}
private connectToWsUrl(url: string, wsKey: string): WebSocket {
this.logger.silly(`Opening WS connection to URL: ${url}`, { ...loggerCategory, wsKey })
const ws = new WebSocket(url);
ws.onopen = event => this.onWsOpen(event, wsKey);
ws.onmessage = event => this.onWsMessage(event, wsKey);
ws.onerror = event => this.onWsError(event, wsKey);
ws.onclose = event => this.onWsClose(event, wsKey);
return ws;
}
private async onWsOpen(event, wsKey: string) {
if (this.wsStore.isConnectionState(wsKey, READY_STATE_CONNECTING)) {
this.logger.info('Websocket connected', { ...loggerCategory, wsKey, livenet: this.isLivenet() });
this.emit('open', { wsKey, event });
} else if (this.wsStore.isConnectionState(wsKey, READY_STATE_RECONNECTING)) {
this.logger.info('Websocket reconnected', { ...loggerCategory, wsKey });
this.emit('reconnected', { wsKey, event });
}
this.setWsState(wsKey, READY_STATE_CONNECTED);
await this.requestTryAuthenticate(wsKey);
this.requestSubscribeTopics(wsKey, [...this.wsStore.getTopics(wsKey)]);
this.wsStore.get(wsKey, true)!.activePingTimer = setInterval(
() => this.ping(wsKey),
this.options.pingInterval
);
}
private onWsMessage(event: MessageEvent, wsKey: string) {
try {
this.clearPongTimer(wsKey);
const msg = parseRawWsMessage(event);
if (msg.channel) {
this.emit('update', msg);
} else {
this.logger.debug('Websocket event: ', event.data || event);
this.onWsMessageResponse(msg, wsKey);
}
} catch (e) {
this.logger.error('Exception parsing ws message: ', { ...loggerCategory, rawEvent: event, wsKey, error: e });
this.emit('error', { wsKey, error: e, rawEvent: event });
}
}
private onWsError(err, wsKey: string) {
this.parseWsError('Websocket error', err, wsKey);
if (this.wsStore.isConnectionState(wsKey, READY_STATE_CONNECTED)) {
this.emit('error', err);
}
}
private onWsClose(event, wsKey: string) {
this.logger.info('Websocket connection closed', { ...loggerCategory, wsKey});
if (this.wsStore.getConnectionState(wsKey) !== READY_STATE_CLOSING && this.options.reconnectOnClose) {
this.reconnectWithDelay(wsKey, this.options.reconnectTimeout!);
this.emit('reconnect');
} else {
this.setWsState(wsKey, READY_STATE_INITIAL);
this.emit('close');
}
}
private onWsMessageResponse(response: any, wsKey: string) {
if (isWsPong(response)) {
this.logger.silly('Received pong', { ...loggerCategory, wsKey });
this.clearPongTimer(wsKey);
} else {
this.emit('response', response);
}
}
private getWs(wsKey: string) {
return this.wsStore.getWs(wsKey);
}
private setWsState(wsKey: string, state: WsConnectionState) {
this.wsStore.setConnectionState(wsKey, state);
}
private getWsKeyForTopic(topic: any) {
return wsKeyGeneral;
}
};