diff --git a/.changeset/socket-mode-close-handshake-timeout.md b/.changeset/socket-mode-close-handshake-timeout.md new file mode 100644 index 000000000..a89b4e40e --- /dev/null +++ b/.changeset/socket-mode-close-handshake-timeout.md @@ -0,0 +1,5 @@ +--- +"@slack/socket-mode": patch +--- + +Fix `disconnect()` taking 5 seconds or more ([#2752](https://github.com/slackapi/node-slack-sdk/issues/2752)). Slack does not close the TCP connection after the close handshake, so `disconnect()` waited until the pong watchdog gave up and logged "A pong wasn't received". The close handshake now times out after 1 second, the heartbeat stops once the close frame is sent, and a close handshake started by Slack is cleaned up on the next heartbeat tick. diff --git a/packages/socket-mode/src/SlackWebSocket.test.ts b/packages/socket-mode/src/SlackWebSocket.test.ts index 00f0bce04..92d18e77c 100644 --- a/packages/socket-mode/src/SlackWebSocket.test.ts +++ b/packages/socket-mode/src/SlackWebSocket.test.ts @@ -151,7 +151,10 @@ describe('SlackWebSocket', () => { assert.strictEqual(sws.readyState, DeadPeerWS.CLOSING, 'socket should be CLOSING after sending close frame'); assert.strictEqual(closeEmitted, false, 'close must not fire before the handshake completes or times out'); - clock.tick(60000); + clock.tick(999); + assert.strictEqual(closeEmitted, false, 'close must not fire before the handshake timeout elapses'); + + clock.tick(1); assert.strictEqual( closeEmitted, @@ -161,6 +164,89 @@ describe('SlackWebSocket', () => { }); }); + describe('heartbeat while closing against a peer that never ends TCP (issue #2752)', () => { + class HalfClosedPeerWS extends EventTarget { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + readyState = HalfClosedPeerWS.OPEN; + close() { + this.readyState = HalfClosedPeerWS.CLOSING; + } + send(_data: string) {} + } + + function open(clientPingTimeoutMS: number) { + const ws = new HalfClosedPeerWS(); + const ping = sandbox.spy(); + const SWS = proxyquire.load('./SlackWebSocket', { + undici: { + WebSocket: class Fake { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + constructor() { + // biome-ignore lint/correctness/noConstructorReturn: for test mocking purposes + return ws; + } + }, + CloseEvent, + ErrorEvent, + MessageEvent, + ping, + }, + }).SlackWebSocket; + const client = new EventEmitter(); + let closeEvents = 0; + client.on('close', () => { + closeEvents += 1; + }); + const logger = new ConsoleLogger(); + const warn = sandbox.stub(logger, 'warn'); + sandbox.stub(logger, 'debug'); + const sws = new SWS({ + url: 'ws://127.0.0.1/', + client, + clientPingTimeoutMS, + serverPingTimeoutMS: 60000, + logger, + }); + sws.connect(); + ws.dispatchEvent(new Event('open')); + return { ws, sws, ping, warn, closeEvents: () => closeEvents }; + } + + it('should stop the heartbeat once the close frame is sent, so the close-handshake timeout owns the wait', () => { + const clock = sandbox.useFakeTimers(); + const { ws, sws, ping, warn, closeEvents } = open(900); + channel('undici:websocket:pong').publish({ websocket: ws, payload: Buffer.from('x') }); + + sws.disconnect(); + const pingsBeforeClose = ping.callCount; + clock.tick(999); + assert.strictEqual(closeEvents(), 0, 'the heartbeat must not cut the close handshake short'); + + clock.tick(1); + + assert.strictEqual(ping.callCount, pingsBeforeClose, 'no ping should be sent while closing'); + assert.strictEqual(closeEvents(), 1); + sinon.assert.notCalled(warn); + }); + + it('should terminate within one heartbeat tick when the peer starts the close handshake', () => { + const clock = sandbox.useFakeTimers(); + const { ws, warn, closeEvents } = open(3000); + + ws.readyState = HalfClosedPeerWS.CLOSING; + clock.tick(1000); + + assert.strictEqual(closeEvents(), 1); + sinon.assert.notCalled(warn); + }); + }); + describe('disconnect() when the connection drops while closing (issue #2771)', () => { class UndiciLikeWS extends EventTarget { static CONNECTING = 0; diff --git a/packages/socket-mode/src/SlackWebSocket.ts b/packages/socket-mode/src/SlackWebSocket.ts index c5540197a..a8b01cbf9 100644 --- a/packages/socket-mode/src/SlackWebSocket.ts +++ b/packages/socket-mode/src/SlackWebSocket.ts @@ -11,7 +11,7 @@ import type { SocketModeDispatcher } from './SocketModeOptions'; export const WS_READY_STATES = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; -const CLOSE_HANDSHAKE_TIMEOUT_MS = 30_000; +const CLOSE_HANDSHAKE_TIMEOUT_MS = 1_000; interface PingPongMessage { websocket: WebSocket; @@ -256,8 +256,9 @@ export class SlackWebSocket { // If we haven't received a close frame yet, then we send one to the peer, expecting to receive a close frame // in response. this.logger.debug('Sending close frame (status=1000).'); + this.stopMonitoringPings(); this.closeHandshakeTimeout = setTimeout(() => { - this.logger.warn('Peer did not complete the close handshake in time; forcing cleanup.'); + this.logger.debug('Peer did not complete the close handshake in time; forcing cleanup.'); this.cleanup(); }, CLOSE_HANDSHAKE_TIMEOUT_MS); this.websocket.close(1000); // 1000 = Normal Closure @@ -291,8 +292,7 @@ export class SlackWebSocket { } this.defaultSocket = null; this.websocket = null; - clearTimeout(this.serverPingTimeout); - clearInterval(this.clientPingTimeout); + this.stopMonitoringPings(); clearTimeout(this.closeHandshakeTimeout); // Emit event back to client letting it know connection has closed (in case it needs to reconnect if // reconnecting is enabled) @@ -346,6 +346,11 @@ export class SlackWebSocket { }, this.options.serverPingTimeoutMS); } + private stopMonitoringPings(): void { + clearTimeout(this.serverPingTimeout); + clearInterval(this.clientPingTimeout); + } + /** * Monitors WebSocket connection health; sends a ping to peer, and expects a pong within a certain timeframe. * If that expectation is not met, we disconnect the websocket. @@ -362,6 +367,11 @@ export class SlackWebSocket { this.logger.error('WebSocket not available, skipping ping.'); return; } + if (this.websocket.readyState === WebSocket.CLOSING) { + this.logger.debug('Peer started the close handshake; terminating WebSocket.'); + this.disconnect(); + return; + } ping(this.websocket, Buffer.from(pingMessage)); if (this.lastPongReceivedTimestamp === undefined) { pingAttemptCount += 1;