-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsocket.ts
More file actions
337 lines (284 loc) · 8.7 KB
/
socket.ts
File metadata and controls
337 lines (284 loc) · 8.7 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
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
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';
/**
* WebSocket close codes that represent an intentional, expected closure.
* See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
*/
const WS_CLOSE_NORMAL = 1000;
const WS_CLOSE_GOING_AWAY = 1001;
/**
* 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 once the connection is 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 times we should attempt reconnection
*/
private reconnectionAttempts: number;
/**
* Page hide event handler reference (for removal)
*/
private pageHideHandler: () => void;
/**
* Timer that closes an idle connection after no errors have been sent
* for connectionIdleMs milliseconds.
*/
private connectionIdleTimer: ReturnType<typeof setTimeout> | null = null;
/**
* How long (ms) to keep the connection open after the last error was sent.
* Errors often come in bursts, so holding the socket briefly avoids
* the overhead of opening a new connection for each one.
*/
private readonly connectionIdleMs: number;
/**
* 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
connectionIdleMs = 10000, // 10 sec — close connection if no new errors arrive
}) {
this.url = collectorEndpoint;
this.onMessage = onMessage;
this.onClose = onClose;
this.onOpen = onOpen;
this.reconnectionTimeout = reconnectionTimeout;
this.reconnectionAttempts = reconnectionAttempts;
this.connectionIdleMs = connectionIdleMs;
this.pageHideHandler = () => {
this.close();
};
this.eventsQueue = [];
this.ws = null;
/**
* Connection is not opened eagerly — it is created on the first send()
* and closed automatically after connectionIdleMs of inactivity.
*/
}
/**
* 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:
this.resetIdleTimer();
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) => {
/**
* Detach handlers and close the previous socket before opening a new one.
* Without this, the old connection stays open and its onclose/onerror
* handlers keep firing, causing duplicate reconnect attempts and log noise.
*/
if (this.ws !== null) {
this.ws.onopen = null;
this.ws.onclose = null;
this.ws.onerror = null;
this.ws.onmessage = null;
this.ws.close();
this.ws = null;
}
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();
/**
* Code 1000 = Normal Closure (intentional), 1001 = Going Away (page unload/navigation).
* These are expected and should not be reported as a lost connection.
* Any other code (e.g. 1006 = Abnormal Closure from idle timeout or infrastructure drop)
* means the connection was lost unexpectedly — notify and reconnect if there are
* queued events waiting to be sent.
*/
const isExpectedClose = [WS_CLOSE_NORMAL, WS_CLOSE_GOING_AWAY].includes(event.code);
if (!isExpectedClose) {
/**
* Cancel the idle timer — it belongs to the now-dead connection.
* A reconnect will set a fresh timer once the new connection is sending.
*/
if (this.connectionIdleTimer !== null) {
clearTimeout(this.connectionIdleTimer);
this.connectionIdleTimer = null;
}
if (typeof this.onClose === 'function') {
this.onClose(event);
}
if (this.eventsQueue.length > 0) {
void this.reconnect();
}
}
};
/**
* 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 and cancels any pending idle timer
*/
private close(): void {
if (this.connectionIdleTimer !== null) {
clearTimeout(this.connectionIdleTimer);
this.connectionIdleTimer = null;
}
if (this.ws === null) {
return;
}
this.ws.onopen = null;
this.ws.onclose = null;
this.ws.onerror = null;
this.ws.onmessage = null;
this.ws.close();
this.ws = null;
}
/**
* Resets the idle close timer.
* Called after each successful send so the connection stays open
* for connectionIdleMs after the last error in a burst.
*/
private resetIdleTimer(): void {
if (this.connectionIdleTimer !== null) {
clearTimeout(this.connectionIdleTimer);
}
this.connectionIdleTimer = setTimeout(() => {
this.connectionIdleTimer = null;
this.close();
}, this.connectionIdleMs);
}
/**
* Tries to reconnect to the server for specified number of times with the interval
*
* @param isForcedCall - call function despite on timer
*/
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);
});
}
}
}