-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathreconnection.js
More file actions
51 lines (44 loc) · 1.21 KB
/
reconnection.js
File metadata and controls
51 lines (44 loc) · 1.21 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
/**
* WebSocket Reconnection Module
* Handles reconnection logic with exponential backoff and jitter.
*/
const constants = require('./constants');
// State
let reconnectAttempts = 0;
let isReconnecting = false;
/**
* Calculate reconnection delay with exponential backoff and jitter.
* @returns {number} - Delay in milliseconds
*/
exports.getReconnectDelay = () => {
const delay = Math.min(
constants.BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts),
constants.MAX_RECONNECT_DELAY,
);
const jitter = delay * constants.JITTER_FACTOR * (Math.random() - 0.5);
reconnectAttempts += 1;
return Math.floor(delay + jitter);
};
/**
* Reset reconnection attempts counter.
*/
exports.resetReconnectDelay = () => {
reconnectAttempts = 0;
};
/**
* Get current reconnection state.
* @returns {boolean} - True if currently reconnecting
*/
exports.getIsReconnecting = () => isReconnecting;
/**
* Set reconnection state.
* @param {boolean} value - New reconnection state
*/
exports.setIsReconnecting = (value) => {
isReconnecting = value;
};
/**
* Get current reconnection attempts count.
* @returns {number} - Number of reconnection attempts
*/
exports.getReconnectAttempts = () => reconnectAttempts;