fix: stop sending pings on every pong

This resulted in endless ping-pong traffic on the websocket, happening
every interval of network latency to the server (e.g. for me, with 40ms
latency to my server, it was about every 40ms). On my server this ended
up taking about 20% of foundkey's CPU usage. Now, just send pings every
30s, and check if we have received any pong's in last 60 seconds to
check that the connection is still alive.

Changelog: Fixed
This commit is contained in:
Ignas Kiela 2023-05-23 10:39:42 +03:00 committed by Johann150
parent 7a94e9f2d5
commit 296c40c5b4
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1

View file

@ -44,18 +44,21 @@ export const initializeStreamingServer = (server: http.Server): void => {
const main = new Connection(socket, ev, user, app);
// ping/pong mechanism
let pingTimeout = null;
function startHeartbeat() {
if (pingTimeout) clearTimeout(pingTimeout);
let pingTimeout: NodeJS.Timeout | null = null;
let disconnectTimeout = setTimeout(() => {
socket.terminate();
}, 60 * SECOND);;
function sendPing() {
socket.ping();
pingTimeout = setTimeout(() => {
socket.terminate();
sendPing();
}, 30 * SECOND);
}
startHeartbeat();
socket.on('ping', () => { startHeartbeat(); });
socket.on('pong', () => { startHeartbeat(); });
function onPong() {
disconnectTimeout.refresh()
}
sendPing();
socket.on('pong', onPong);
// keep user "online" while a stream is connected
const intervalId = user ? setInterval(() => {
@ -75,6 +78,7 @@ export const initializeStreamingServer = (server: http.Server): void => {
redisClient.off('message', onRedisMessage);
if (intervalId) clearInterval(intervalId);
if (pingTimeout) clearTimeout(pingTimeout);
if (disconnectTimeout) clearTimeout(disconnectTimeout);
});
});
});