From 56e67185fc346e04e5d1adad8d7bfb932336cf93 Mon Sep 17 00:00:00 2001 From: Voxelli <69213593+legendhimself@users.noreply.github.com> Date: Mon, 2 Jan 2023 20:28:08 +0530 Subject: [PATCH] fix(websocketshard): backport zombie connection fix (#9003) --- src/client/websocket/WebSocketShard.js | 33 ++++++++++++-------------- test/shard.js | 2 +- 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/client/websocket/WebSocketShard.js b/src/client/websocket/WebSocketShard.js index 3577a280e..0c59f8019 100644 --- a/src/client/websocket/WebSocketShard.js +++ b/src/client/websocket/WebSocketShard.js @@ -578,14 +578,10 @@ class WebSocketShard extends EventEmitter { } this.wsCloseTimeout = setTimeout(() => { this.setWsCloseTimeout(-1); - this.debug(`[WebSocket] Close Emitted: ${this.closeEmitted}`); + // Check if close event was emitted. if (this.closeEmitted) { - this.debug( - `[WebSocket] was closed. | WS State: ${ - CONNECTION_STATE[this.connection?.readyState ?? WebSocket.CLOSED] - } | Close Emitted: ${this.closeEmitted}`, - ); + this.debug(`[WebSocket] close was already emitted, assuming the connection was closed properly.`); // Setting the variable false to check for zombie connections. this.closeEmitted = false; return; @@ -593,13 +589,17 @@ class WebSocketShard extends EventEmitter { this.debug( // eslint-disable-next-line max-len - `[WebSocket] did not close properly, assuming a zombie connection.\nEmitting close and reconnecting again.`, + `[WebSocket] Close Emitted: ${this.closeEmitted} | did not close properly, assuming a zombie connection.\nEmitting close and reconnecting again.`, ); - this.emitClose(); - // Setting the variable false to check for zombie connections. - this.closeEmitted = false; - }, time).unref(); + if (this.connection) this._cleanupConnection(); + + this.emitClose({ + code: 4009, + reason: 'Session time out.', + wasClean: false, + }); + }, time); } /** @@ -824,14 +824,11 @@ class WebSocketShard extends EventEmitter { this._emitDestroyed(); } - if (this.connection?.readyState === WebSocket.CLOSING || this.connection?.readyState === WebSocket.CLOSED) { - this.closeEmitted = false; - this.debug( - `[WebSocket] Adding a WebSocket close timeout to ensure a correct WS reconnect. + this.debug( + `[WebSocket] Adding a WebSocket close timeout to ensure a correct WS reconnect. Timeout: ${this.manager.client.options.closeTimeout}ms`, - ); - this.setWsCloseTimeout(this.manager.client.options.closeTimeout); - } + ); + this.setWsCloseTimeout(this.manager.client.options.closeTimeout); // Step 2: Null the connection object this.connection = null; diff --git a/test/shard.js b/test/shard.js index 25751d940..f8d6f3573 100644 --- a/test/shard.js +++ b/test/shard.js @@ -26,7 +26,7 @@ process.send(123); client.on('ready', () => { console.log('Ready', client.options.shards); - if (client.options.shards === 0) { + if (client.options.shards[0] === 0) { setTimeout(() => { console.log('kek dying'); client.destroy();