-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsocket.ts
More file actions
292 lines (249 loc) · 7.94 KB
/
socket.ts
File metadata and controls
292 lines (249 loc) · 7.94 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
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';
import { singleFlight } from '../utils/single-flight';
/**
* 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;
/**
* 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;
/**
* Deduplicates concurrent openConnection() calls — all callers share the
* same in-flight Promise so only one WebSocket is ever created at a time.
*/
private readonly initOnce: () => Promise<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
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 => {},
connectionIdleMs = 10000, // 10 sec — close connection if no new errors arrive
}) {
this.url = collectorEndpoint;
this.onMessage = onMessage;
this.onClose = onClose;
this.onOpen = onOpen;
this.connectionIdleMs = connectionIdleMs;
this.pageHideHandler = () => {
this.close();
};
this.eventsQueue = [];
this.ws = null;
this.initOnce = singleFlight(() => this.openConnection());
/**
* 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> {
this.eventsQueue.push(message);
if (this.ws !== null && this.ws.readyState === WebSocket.CLOSED) {
this.closeAndDetachSocket();
}
if (this.ws === null) {
await this.initOnce();
}
if (this.ws !== null && this.ws.readyState === WebSocket.OPEN) {
this.sendQueue();
}
}
/**
* 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.
* Always call initOnce() instead — it deduplicates concurrent calls.
*/
private openConnection(): Promise<void> {
return new Promise((resolve, reject) => {
this.closeAndDetachSocket();
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.
*/
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 fresh timer will be set once the next send() opens a new connection.
*/
if (this.connectionIdleTimer !== null) {
clearTimeout(this.connectionIdleTimer);
this.connectionIdleTimer = null;
}
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 and cancels any pending idle timer
*/
private close(): void {
if (this.connectionIdleTimer !== null) {
clearTimeout(this.connectionIdleTimer);
this.connectionIdleTimer = null;
}
this.closeAndDetachSocket();
}
/**
* Closes the WebSocket and nulls all event handlers before releasing the reference.
* Without this, the old connection stays open and its onclose/onerror
* handlers keep firing, causing duplicate reconnect attempts and log noise.
*/
private closeAndDetachSocket(): void {
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;
/**
* onclose is nulled above so it won't fire — call destroyListeners() directly
* to ensure the pagehide listener is always removed on explicit close.
*/
this.destroyListeners();
}
/**
* 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);
}
/**
* Sends all queued events directly via the WebSocket.
* Bypasses send() intentionally — send() always enqueues first,
* so calling it here would cause infinite recursion.
*/
private sendQueue(): void {
if (this.ws === null || this.ws.readyState !== WebSocket.OPEN) {
return;
}
this.resetIdleTimer();
while (this.eventsQueue.length) {
const event = this.eventsQueue.shift();
if (!event) {
continue;
}
try {
this.ws.send(JSON.stringify(event));
} catch (sendingError) {
log('WebSocket sending error', 'error', sendingError);
}
}
}
}