Skip to content

Commit 1d3a1af

Browse files
WilliamBergaminGrmiadeClaude
authored
fix(socket-mode): stop waiting on a close handshake Slack never completes (#2819)
Co-authored-by: Grmiade <jeremy@payfit.com> Co-authored-by: Claude <svc-devxp-claude@slack-corp.com>
1 parent 5548d67 commit 1d3a1af

3 files changed

Lines changed: 106 additions & 5 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@slack/socket-mode": patch
3+
---
4+
5+
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.

‎packages/socket-mode/src/SlackWebSocket.test.ts‎

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,10 @@ describe('SlackWebSocket', () => {
151151
assert.strictEqual(sws.readyState, DeadPeerWS.CLOSING, 'socket should be CLOSING after sending close frame');
152152
assert.strictEqual(closeEmitted, false, 'close must not fire before the handshake completes or times out');
153153

154-
clock.tick(60000);
154+
clock.tick(999);
155+
assert.strictEqual(closeEmitted, false, 'close must not fire before the handshake timeout elapses');
156+
157+
clock.tick(1);
155158

156159
assert.strictEqual(
157160
closeEmitted,
@@ -161,6 +164,89 @@ describe('SlackWebSocket', () => {
161164
});
162165
});
163166

167+
describe('heartbeat while closing against a peer that never ends TCP (issue #2752)', () => {
168+
class HalfClosedPeerWS extends EventTarget {
169+
static CONNECTING = 0;
170+
static OPEN = 1;
171+
static CLOSING = 2;
172+
static CLOSED = 3;
173+
readyState = HalfClosedPeerWS.OPEN;
174+
close() {
175+
this.readyState = HalfClosedPeerWS.CLOSING;
176+
}
177+
send(_data: string) {}
178+
}
179+
180+
function open(clientPingTimeoutMS: number) {
181+
const ws = new HalfClosedPeerWS();
182+
const ping = sandbox.spy();
183+
const SWS = proxyquire.load('./SlackWebSocket', {
184+
undici: {
185+
WebSocket: class Fake {
186+
static CONNECTING = 0;
187+
static OPEN = 1;
188+
static CLOSING = 2;
189+
static CLOSED = 3;
190+
constructor() {
191+
// biome-ignore lint/correctness/noConstructorReturn: for test mocking purposes
192+
return ws;
193+
}
194+
},
195+
CloseEvent,
196+
ErrorEvent,
197+
MessageEvent,
198+
ping,
199+
},
200+
}).SlackWebSocket;
201+
const client = new EventEmitter();
202+
let closeEvents = 0;
203+
client.on('close', () => {
204+
closeEvents += 1;
205+
});
206+
const logger = new ConsoleLogger();
207+
const warn = sandbox.stub(logger, 'warn');
208+
sandbox.stub(logger, 'debug');
209+
const sws = new SWS({
210+
url: 'ws://127.0.0.1/',
211+
client,
212+
clientPingTimeoutMS,
213+
serverPingTimeoutMS: 60000,
214+
logger,
215+
});
216+
sws.connect();
217+
ws.dispatchEvent(new Event('open'));
218+
return { ws, sws, ping, warn, closeEvents: () => closeEvents };
219+
}
220+
221+
it('should stop the heartbeat once the close frame is sent, so the close-handshake timeout owns the wait', () => {
222+
const clock = sandbox.useFakeTimers();
223+
const { ws, sws, ping, warn, closeEvents } = open(900);
224+
channel('undici:websocket:pong').publish({ websocket: ws, payload: Buffer.from('x') });
225+
226+
sws.disconnect();
227+
const pingsBeforeClose = ping.callCount;
228+
clock.tick(999);
229+
assert.strictEqual(closeEvents(), 0, 'the heartbeat must not cut the close handshake short');
230+
231+
clock.tick(1);
232+
233+
assert.strictEqual(ping.callCount, pingsBeforeClose, 'no ping should be sent while closing');
234+
assert.strictEqual(closeEvents(), 1);
235+
sinon.assert.notCalled(warn);
236+
});
237+
238+
it('should terminate within one heartbeat tick when the peer starts the close handshake', () => {
239+
const clock = sandbox.useFakeTimers();
240+
const { ws, warn, closeEvents } = open(3000);
241+
242+
ws.readyState = HalfClosedPeerWS.CLOSING;
243+
clock.tick(1000);
244+
245+
assert.strictEqual(closeEvents(), 1);
246+
sinon.assert.notCalled(warn);
247+
});
248+
});
249+
164250
describe('disconnect() when the connection drops while closing (issue #2771)', () => {
165251
class UndiciLikeWS extends EventTarget {
166252
static CONNECTING = 0;

‎packages/socket-mode/src/SlackWebSocket.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type { SocketModeDispatcher } from './SocketModeOptions';
1111

1212
export const WS_READY_STATES = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
1313

14-
const CLOSE_HANDSHAKE_TIMEOUT_MS = 30_000;
14+
const CLOSE_HANDSHAKE_TIMEOUT_MS = 1_000;
1515

1616
interface PingPongMessage {
1717
websocket: WebSocket;
@@ -256,8 +256,9 @@ export class SlackWebSocket {
256256
// If we haven't received a close frame yet, then we send one to the peer, expecting to receive a close frame
257257
// in response.
258258
this.logger.debug('Sending close frame (status=1000).');
259+
this.stopMonitoringPings();
259260
this.closeHandshakeTimeout = setTimeout(() => {
260-
this.logger.warn('Peer did not complete the close handshake in time; forcing cleanup.');
261+
this.logger.debug('Peer did not complete the close handshake in time; forcing cleanup.');
261262
this.cleanup();
262263
}, CLOSE_HANDSHAKE_TIMEOUT_MS);
263264
this.websocket.close(1000); // 1000 = Normal Closure
@@ -291,8 +292,7 @@ export class SlackWebSocket {
291292
}
292293
this.defaultSocket = null;
293294
this.websocket = null;
294-
clearTimeout(this.serverPingTimeout);
295-
clearInterval(this.clientPingTimeout);
295+
this.stopMonitoringPings();
296296
clearTimeout(this.closeHandshakeTimeout);
297297
// Emit event back to client letting it know connection has closed (in case it needs to reconnect if
298298
// reconnecting is enabled)
@@ -346,6 +346,11 @@ export class SlackWebSocket {
346346
}, this.options.serverPingTimeoutMS);
347347
}
348348

349+
private stopMonitoringPings(): void {
350+
clearTimeout(this.serverPingTimeout);
351+
clearInterval(this.clientPingTimeout);
352+
}
353+
349354
/**
350355
* Monitors WebSocket connection health; sends a ping to peer, and expects a pong within a certain timeframe.
351356
* If that expectation is not met, we disconnect the websocket.
@@ -362,6 +367,11 @@ export class SlackWebSocket {
362367
this.logger.error('WebSocket not available, skipping ping.');
363368
return;
364369
}
370+
if (this.websocket.readyState === WebSocket.CLOSING) {
371+
this.logger.debug('Peer started the close handshake; terminating WebSocket.');
372+
this.disconnect();
373+
return;
374+
}
365375
ping(this.websocket, Buffer.from(pingMessage));
366376
if (this.lastPongReceivedTimestamp === undefined) {
367377
pingAttemptCount += 1;

0 commit comments

Comments
 (0)