-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsocket.ts
More file actions
255 lines (214 loc) · 5.76 KB
/
socket.ts
File metadata and controls
255 lines (214 loc) · 5.76 KB
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
import type { Transport } from '@hawk.so/core';
import { log } from '@hawk.so/core';
import type { CatcherMessage } from '@/types';
import type { CatcherMessageType } from '@hawk.so/types';
/**
* Custom WebSocket wrapper class
*
* @copyright CodeX
*/
export default class Socket<T extends CatcherMessageType = 'errors/javascript'> implements Transport<T> {
/**
* Socket connection endpoint
*/
private readonly url: string;
/**
* External handler for socket message
*/
private readonly onMessage: (message: MessageEvent) => void;
/**
* External handler for socket opening
*/
private readonly onOpen: (event: Event) => void;
/**
* External handler for socket close
*/
private readonly onClose: (event: CloseEvent) => void;
/**
* Queue of events collected while socket is not connected
* They will be sent when connection will be established
*/
private eventsQueue: CatcherMessage<T>[];
/**
* Websocket instance
*/
private ws: WebSocket | null;
/**
* Reconnection tryings Timeout
*/
private reconnectionTimer: unknown;
/**
* Time between reconnection attempts
*/
private readonly reconnectionTimeout: number;
/**
* How many time we should attempt reconnection
*/
private reconnectionAttempts: number;
/**
* Page hide event handler reference (for removal)
*/
private pageHideHandler: () => void;
/**
* Creates new Socket instance. Setup initial socket params.
*
* @param options — constructor options for catcher initialization
*/
constructor({
collectorEndpoint,
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onMessage = (message: MessageEvent): void => {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
onClose = (): void => {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
onOpen = (): void => {},
reconnectionAttempts = 5,
reconnectionTimeout = 10000, // 10 * 1000 ms = 10 sec
}) {
this.url = collectorEndpoint;
this.onMessage = onMessage;
this.onClose = onClose;
this.onOpen = onOpen;
this.reconnectionTimeout = reconnectionTimeout;
this.reconnectionAttempts = reconnectionAttempts;
this.pageHideHandler = () => {
this.close();
};
this.eventsQueue = [];
this.ws = null;
this.init()
.then(() => {
/**
* Send queued events if exists
*/
this.sendQueue();
})
.catch((error) => {
log('WebSocket error', 'error', error);
});
}
/**
* Send an event to the Collector
*
* @param message - event data in Hawk Format
*/
public async send(message: CatcherMessage<T>): Promise<void> {
if (this.ws === null) {
this.eventsQueue.push(message);
await this.init();
this.sendQueue();
return;
}
switch (this.ws.readyState) {
case WebSocket.OPEN:
return this.ws.send(JSON.stringify(message));
case WebSocket.CLOSED:
this.eventsQueue.push(message);
return this.reconnect();
case WebSocket.CONNECTING:
case WebSocket.CLOSING:
this.eventsQueue.push(message);
}
}
/**
* Setup window event listeners
*/
private setupListeners(): void {
window.addEventListener('pagehide', this.pageHideHandler, { capture: true });
}
/**
* Remove window event listeners
*/
private destroyListeners(): void {
window.removeEventListener('pagehide', this.pageHideHandler, { capture: true });
}
/**
* Create new WebSocket connection and setup socket event listeners
*/
private init(): Promise<void> {
return new Promise((resolve, reject) => {
this.ws = new WebSocket(this.url);
/**
* New message handler
*/
if (typeof this.onMessage === 'function') {
this.ws.onmessage = this.onMessage;
}
/**
* Connection closing handler
*
* @param event - websocket event on closing
*/
this.ws.onclose = (event: CloseEvent): void => {
this.destroyListeners();
if (typeof this.onClose === 'function') {
this.onClose(event);
}
};
/**
* Error handler
*
* @param event - websocket event on error
*/
this.ws.onerror = (event: Event): void => {
reject(event);
};
this.ws.onopen = (event: Event): void => {
this.setupListeners();
if (typeof this.onOpen === 'function') {
this.onOpen(event);
}
resolve();
};
});
}
/**
* Closes socket connection
*/
private close(): void {
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
/**
* Tries to reconnect to the server for specified number of times with the interval
*
* @param {boolean} [isForcedCall] - call function despite on timer
* @returns {Promise<void>}
*/
private async reconnect(isForcedCall = false): Promise<void> {
if (this.reconnectionTimer && !isForcedCall) {
return;
}
this.reconnectionTimer = null;
try {
await this.init();
log('Successfully reconnected.', 'info');
this.sendQueue();
} catch (error) {
this.reconnectionAttempts--;
if (this.reconnectionAttempts === 0) {
return;
}
this.reconnectionTimer = setTimeout(() => {
void this.reconnect(true);
}, this.reconnectionTimeout);
}
}
/**
* Sends all queued events one-by-one
*/
private sendQueue(): void {
while (this.eventsQueue.length) {
const event = this.eventsQueue.shift();
if (!event) {
continue;
}
this.send(event)
.catch((sendingError) => {
log('WebSocket sending error', 'error', sendingError);
});
}
}
}