fix: stop sending pings on every pong
ci/woodpecker/pr/lint-backend Pipeline was successful Details
ci/woodpecker/pr/lint-foundkey-js Pipeline was successful Details
ci/woodpecker/pr/build Pipeline was successful Details
ci/woodpecker/pr/lint-client Pipeline was successful Details
ci/woodpecker/pr/lint-sw Pipeline was successful Details
ci/woodpecker/pr/test Pipeline was successful Details

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
parent 7a94e9f2d5
commit f7df989679
1 changed files with 12 additions and 8 deletions

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);
});
});
});