kannon/classes/Heartbeat.js

64 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-04-14 14:23:41 +02:00
const sleep = require('../libs/util.js').sleep;
const EventEmitter = require('events');
const Message = require('./Message.js');
class Heartbeat extends EventEmitter {
constructor(client) {
super();
2022-04-20 16:15:33 +02:00
this.interval = config?.heartbeat || 10000;
2022-04-14 14:23:41 +02:00
this.client = client;
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 sleep(this.interval);
}
this.alive = false;
2022-04-29 16:50:56 +02:00
// this.ping = process.hrtime.bigint();
this.ping = Date.now();
2022-04-21 13:09:31 +02:00
await new Message('ping').send(this.client);
2022-04-14 14:23:41 +02:00
this.timeout = setTimeout(() => {
this.#sendPing();
}, this.interval);
}
async #listenForPingPong() {
2022-04-20 16:15:33 +02:00
eventparser.on('ping', () => {
2022-04-14 14:23:41 +02:00
logger.debug(this.client.getTag() + ' handling event \'ping\', responding with \'pong\'...');
new Message('pong').send(this.client);
});
2022-04-21 13:09:31 +02:00
eventparser.on('pong', () => {
2022-04-14 14:23:41 +02:00
logger.debug(this.client.getTag() + ' handling event \'pong\'...');
this.alive = true;
2022-04-29 16:50:56 +02:00
// this.pong = process.hrtime.bigint();
this.pong = Date.now();
2022-04-21 13:09:31 +02:00
this.latency = this.pong - this.ping;
this.emit('network-statistics', {
2022-04-29 16:50:56 +02:00
ping: this.ping,
pong: this.pong,
latency: this.latency
2022-04-14 14:23:41 +02:00
});
});
}
destroy() {
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
}
2022-04-20 16:15:33 +02:00
eventparser.removeAllListeners('ping');
eventparser.removeAllListeners('pong');
2022-04-14 14:23:41 +02:00
}
}
module.exports = Heartbeat;