2022-04-14 14:25:48 +02:00
|
|
|
const EventEmitter = require('events');
|
|
|
|
const Message = require('./Message.js');
|
|
|
|
|
|
|
|
class Heartbeat extends EventEmitter {
|
|
|
|
|
|
|
|
constructor(eventParser) {
|
|
|
|
super();
|
|
|
|
this.interval = config?.server?.heartbeat || 10000;
|
|
|
|
this.eventParser = eventParser;
|
|
|
|
this.#listenForPingPong();
|
|
|
|
this.#sendPing();
|
|
|
|
}
|
|
|
|
|
|
|
|
async #sendPing() {
|
|
|
|
if (this.timeout !== undefined) {
|
|
|
|
clearTimeout(this.timeout);
|
|
|
|
}
|
|
|
|
if (this.alive === false) {
|
|
|
|
this.emit('timeout');
|
|
|
|
return;
|
|
|
|
} else if (this.alive === undefined) {
|
|
|
|
await new Promise((resolve, reject) => {
|
|
|
|
setTimeout(resolve, this.interval);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
this.alive = false;
|
|
|
|
await new Message('ping').send();
|
|
|
|
this.timeout = setTimeout(() => {
|
|
|
|
this.#sendPing();
|
|
|
|
}, this.interval);
|
|
|
|
}
|
|
|
|
|
|
|
|
async #listenForPingPong() {
|
2022-04-21 13:40:00 +02:00
|
|
|
this.eventParser.on('ping', () => {
|
2022-04-14 14:25:48 +02:00
|
|
|
logger.debug('handling event \'ping\', responding with \'pong\'...');
|
2022-04-21 13:40:00 +02:00
|
|
|
new Message('pong').send();
|
2022-04-14 14:25:48 +02:00
|
|
|
});
|
|
|
|
this.eventParser.on('pong', () => {
|
|
|
|
logger.debug('handling event \'pong\'...');
|
|
|
|
this.alive = true;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
destroy() {
|
|
|
|
if (this.timeout !== undefined) {
|
|
|
|
clearTimeout(this.timeout);
|
|
|
|
}
|
|
|
|
this.eventParser.removeAllListeners('ping');
|
|
|
|
this.eventParser.removeAllListeners('pong');
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Heartbeat;
|