Skip to content

Commit

Permalink
refactor: improve missed heartbeat warning
Browse files Browse the repository at this point in the history
  • Loading branch information
b-ma committed May 23, 2024
1 parent f191970 commit b2b25d5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
6 changes: 1 addition & 5 deletions src/server/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
15 changes: 8 additions & 7 deletions src/server/Socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down

0 comments on commit b2b25d5

Please sign in to comment.