From afc099f4aca113c43f0852ae8a1350faf4ffcaa0 Mon Sep 17 00:00:00 2001 From: tiagosiebler Date: Fri, 22 Dec 2023 12:00:42 +0000 Subject: [PATCH] feat(): slight improvement around ws teardown. feat(#305): implement safe terminate for browsers --- src/util/websocket-util.ts | 14 ++++++++++++++ src/websocket-client.ts | 10 ++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/util/websocket-util.ts b/src/util/websocket-util.ts index a2d27f83..400b81f1 100644 --- a/src/util/websocket-util.ts +++ b/src/util/websocket-util.ts @@ -1,3 +1,5 @@ +import WebSocket from 'isomorphic-ws'; + import { APIMarket, CategoryV5, WsKey } from '../types'; import { DefaultLogger } from './logger'; @@ -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(); + } +} diff --git a/src/websocket-client.ts b/src/websocket-client.ts index e8f0d5e1..595243ea 100644 --- a/src/websocket-client.ts +++ b/src/websocket-client.ts @@ -40,6 +40,7 @@ import { isTopicSubscriptionSuccess, isWsPong, neverGuard, + safeTerminateWs, serializeParams, } from './util'; import { RestClientV5 } from './rest-client-v5'; @@ -462,7 +463,7 @@ export class WebsocketClient extends EventEmitter { const ws = this.getWs(wsKey); ws?.close(); if (force) { - ws?.terminate(); + safeTerminateWs(ws); } } @@ -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(