Skip to content

Commit 75f0a50

Browse files
committed
fix(WebSocketShard): retry on 5xx error
1 parent 5c90b7f commit 75f0a50

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

packages/ws/src/ws/WebSocketShard.ts

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Buffer } from 'node:buffer';
22
import { once } from 'node:events';
3+
import type { IncomingMessage } from 'node:http';
34
import { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';
45
import { setTimeout as sleep } from 'node:timers/promises';
56
import { URLSearchParams } from 'node:url';
@@ -252,21 +253,25 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
252253

253254
connection.binaryType = 'arraybuffer';
254255

255-
connection.onmessage = (event) => {
256-
void this.onMessage(event.data, event.data instanceof ArrayBuffer);
257-
};
256+
connection.on('message', (event) => {
257+
void this.onMessage(event, event instanceof ArrayBuffer);
258+
});
258259

259-
connection.onerror = (event) => {
260-
this.onError(event.error);
261-
};
260+
connection.on('error', (event) => {
261+
this.onError(event);
262+
});
262263

263-
connection.onclose = (event) => {
264-
void this.onClose(event.code);
265-
};
264+
connection.on('close', (code) => {
265+
void this.onClose(code);
266+
});
266267

267-
connection.onopen = () => {
268+
connection.on('open', () => {
268269
this.sendRateLimitState = getInitialSendRateLimitState();
269-
};
270+
});
271+
272+
connection.on('unexpected-response', (_, response) => {
273+
this.onUnexpectedResponse(response);
274+
});
270275

271276
this.connection = connection;
272277

@@ -800,6 +805,19 @@ export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
800805
this.emit(WebSocketShardEvents.Error, error);
801806
}
802807

808+
private onUnexpectedResponse(response: IncomingMessage) {
809+
if (response.statusCode && response.statusCode >= 500) {
810+
this.debug(['Received a 5xx response from the server, retrying']);
811+
this.failedToConnectDueToNetworkError = true;
812+
return;
813+
}
814+
815+
this.emit(
816+
WebSocketShardEvents.Error,
817+
new Error(`Unexpected response from the server: ${response.statusCode ?? 'unknown'}`),
818+
);
819+
}
820+
803821
private async onClose(code: number) {
804822
this.emit(WebSocketShardEvents.Closed, code);
805823

0 commit comments

Comments
 (0)