From acdafe60c7aa1ac5a3d358934c055c297080a944 Mon Sep 17 00:00:00 2001 From: DD Date: Tue, 16 Aug 2022 18:33:00 +0300 Subject: [PATCH] fix(WebSocketShard#destroy): wait for close and cleanup listeners (#8479) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> --- packages/ws/src/ws/WebSocketShard.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/ws/src/ws/WebSocketShard.ts b/packages/ws/src/ws/WebSocketShard.ts index 9cd23878ce05..88b6c8b2582d 100644 --- a/packages/ws/src/ws/WebSocketShard.ts +++ b/packages/ws/src/ws/WebSocketShard.ts @@ -185,7 +185,18 @@ export class WebSocketShard extends AsyncEventEmitter { this.connection && (this.connection.readyState === WebSocket.OPEN || this.connection.readyState === WebSocket.CONNECTING) ) { + // No longer need to listen to messages + this.connection.removeAllListeners('message'); + // Prevent a reconnection loop by unbinding the main close event + this.connection.removeAllListeners('close'); this.connection.close(options.code, options.reason); + + // Actually wait for the connection to close + await once(this.connection, 'close'); + + // Lastly, remove the error event. + // Doing this earlier would cause a hard crash in case an error event fired on our `close` call + this.connection.removeAllListeners('error'); } this.status = WebSocketShardStatus.Idle;