-
Notifications
You must be signed in to change notification settings - Fork 2
/
HeartbeatHandler.ts
97 lines (76 loc) · 2.66 KB
/
HeartbeatHandler.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
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
import * as WebSocket from "ws";
import {isNullOrUndefined} from "util";
import Timer = NodeJS.Timer;
/**
* Actively handles the heartbeat ping/pong mechanism respecting
* the specified parameters.
*/
export class HeartbeatHandler {
private readonly STATE_OPEN: number = 1;
private readonly STATE_CLOSED: number = 3;
private websocket: WebSocket;
private pingInterval: number;
private onDeath: () => any;
private alive: boolean;
/**
* Default constructor.
*
* @param websocket The web socket instance on which we want to
* perform the checks and start the monitoring.
* @param pingInterval The interval between which ping/pong messages
* are exchanged between client and server
* (defaults to 1 minute).
* @param onDeath Callback called on client/server connection end,
* detected from missing heartbeat updates.
*/
constructor(
websocket: WebSocket,
pingInterval: number,
onDeath?: () => any ) {
this.websocket = websocket;
this.pingInterval = pingInterval;
this.onDeath = onDeath;
this.alive = true;
}
/**
* Does some basic checks about the web socket state and starts
* the actual heartbeat monitoring.
*/
public handle(): void {
this.websocket.on( "pong", () => {
this.alive = true;
} );
if( this.websocket.readyState !== this.STATE_OPEN ) {
this.websocket.on( "open", () => {
this.handleHeartbeat();
} );
return;
}
this.handleHeartbeat();
}
/**
* Implements the business logic required for the heartbeat detection to work.
* If the heartbeat stops respecting the previously-set timeout, the client/server
* connection is considered dead and the eventually passed in callback is called.
* The web socket is also closed with code 1008 (policy violation) and message
* "Heartbeat stopped".
*/
private handleHeartbeat(): void {
let timer: Timer = setInterval( () => {
if( this.websocket.readyState === this.STATE_CLOSED ) {
clearInterval( timer );
return;
}
if( !this.alive ) {
if( !isNullOrUndefined( this.onDeath ) ) {
this.onDeath();
}
this.websocket.terminate();
clearInterval( timer );
return;
}
this.alive = false;
this.websocket.ping();
}, this.pingInterval );
}
}