-
Notifications
You must be signed in to change notification settings - Fork 46
/
echoTracker.ts
56 lines (39 loc) · 1.79 KB
/
echoTracker.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
/**
* This script keeps track of the echos we are expecting from recent websocket-out messages.
*
* Typically, if we don't receive an echo within five seconds,
* we think the connection was lost, so we terminate the websocket.
*/
// Variables ---------------------------------------------------------------------------
/**
*
* An object containing the timeout ID's for the timers that auto terminate
* websockets if we never hear an echo back: `{ messageID: timeoutID }`
*/
const echoTimers: { [messageID: number]: NodeJS.Timeout | number } = {};
/**
* The time, after which we don't hear an expected echo from a websocket,
* in which it be assumed disconnected, and auto terminated, in milliseconds.
*/
const timeToWaitForEchoMillis: number = 5000; // 5 seconds until we assume we've disconnected!
// Functions ---------------------------------------------------------------------------
function addTimeoutToEchoTimers(messageID: number, timeout: NodeJS.Timeout | number) {
echoTimers[messageID] = timeout;
}
/**
* Cancel the timer that will close the socket when we don't hear an expected echo from a sent socket message.
* If there was no timer, this will return false, meaning it was an invalid echo.
*/
function deleteEchoTimerForMessageID(messageIDEchoIsFor: any): boolean {
if (typeof messageIDEchoIsFor !== 'number') return false; // Invalid echo (incoming socket message didn't include an echo ID)
const timeout: NodeJS.Timeout | number | undefined = echoTimers[messageIDEchoIsFor];
if (timeout === undefined) return false; // Invalid echo (message ID wasn't from any recently sent socket message)
clearTimeout(timeout);
delete echoTimers[messageIDEchoIsFor];
return true; // Valid echo
}
export {
addTimeoutToEchoTimers,
deleteEchoTimerForMessageID,
timeToWaitForEchoMillis,
};