From b2b25d56c24d197d90672024e7eb8fc8292d9aaf Mon Sep 17 00:00:00 2001 From: b-ma Date: Thu, 23 May 2024 16:41:58 +0200 Subject: [PATCH] refactor: improve missed heartbeat warning --- src/server/Server.js | 6 +----- src/server/Socket.js | 15 ++++++++------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/server/Server.js b/src/server/Server.js index 7d394e42..d416aace 100644 --- a/src/server/Server.js +++ b/src/server/Server.js @@ -846,11 +846,7 @@ Invalid certificate files, please check your: // this has been validated if (this.isProtected(role) && this.isValidConnectionToken(connectionToken)) { const { ip } = decryptData(connectionToken); - const newData = { - ip: ip, - id: client.id, - }; - + const newData = { ip, id: client.id }; const newToken = encryptData(newData); client.token = newToken; diff --git a/src/server/Socket.js b/src/server/Socket.js index 2c324b32..4674e5e5 100644 --- a/src/server/Socket.js +++ b/src/server/Socket.js @@ -68,13 +68,12 @@ class Socket { }, }; - let isAlive = true; - + let heartbeatMissed = 0; // heartbeat system (run only on string socket), adapted from: // https://github.com/websockets/ws#how-to-detect-and-close-broken-connections this.#socket.addEventListener('message', e => { if (e.data === PONG_MESSAGE) { - isAlive = true; + heartbeatMissed = 0; msg.value.pong = getTime(); this.#sockets[kSocketsLatencyStatsWorker].postMessage(msg); @@ -87,18 +86,20 @@ class Socket { }); this.#heartbeatId = setInterval(() => { - if (isAlive === false) { + // we didn't receive the pong message + if (heartbeatMissed > 0) { // Emit a 'close' event to go trough all the disconnection pipeline // // @note - this seems to create false positive disconnections when // client is busy, e.g. when loading large sound files so let's just warn // until we gather more feedback + // cf. https://making.close.com/posts/reliable-websockets/ + console.warn(`[Socket] client (id: ${this[kSocketClientId]}) did not respond to ping message in time (missed: ${heartbeatMissed}, interval: ${PING_INTERVAL})`); // this.#dispatchEvent('close'); - console.warn(`[Socket] client (id: ${this[kSocketClientId]}) did not respond to ping message in time, interval: ${PING_INTERVAL}`); - return; + // return; } - isAlive = false; + heartbeatMissed += 1; msg.value.ping = getTime(); this.#socket.send(PING_MESSAGE);