Skip to content

Commit

Permalink
feat(): slight improvement around ws teardown. feat(#305): implement …
Browse files Browse the repository at this point in the history
…safe terminate for browsers
  • Loading branch information
tiagosiebler committed Dec 22, 2023
1 parent 2240bd4 commit afc099f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/util/websocket-util.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import WebSocket from 'isomorphic-ws';

import { APIMarket, CategoryV5, WsKey } from '../types';
import { DefaultLogger } from './logger';

Expand Down Expand Up @@ -548,3 +550,15 @@ export const WS_ERROR_ENUM = {
export function neverGuard(x: never, msg: string): Error {
return new Error(`Unhandled value exception "x", ${msg}`);
}

/**
* #305: ws.terminate() is undefined in browsers.
* This only works in node.js, not in browsers.
* Does nothing if `ws` is undefined.
*/
export function safeTerminateWs(ws?: WebSocket | unknown) {
// #305: ws.terminate() undefined in browsers
if (ws && typeof ws['terminate'] === 'function') {
ws.terminate();
}
}
10 changes: 8 additions & 2 deletions src/websocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
isTopicSubscriptionSuccess,
isWsPong,
neverGuard,
safeTerminateWs,
serializeParams,
} from './util';
import { RestClientV5 } from './rest-client-v5';
Expand Down Expand Up @@ -462,7 +463,7 @@ export class WebsocketClient extends EventEmitter {
const ws = this.getWs(wsKey);
ws?.close();
if (force) {
ws?.terminate();
safeTerminateWs(ws);
}
}

Expand Down Expand Up @@ -811,7 +812,12 @@ export class WebsocketClient extends EventEmitter {
this.clearPingTimer(wsKey);
this.clearPongTimer(wsKey);

this.getWs(wsKey)?.terminate();
const ws = this.getWs(wsKey);

if (ws) {
ws.close();
safeTerminateWs(ws);
}

if (!wasOpen) {
this.logger.info(
Expand Down

0 comments on commit afc099f

Please sign in to comment.