Merge pull request #20 from orionprotocol/fix/OP-2481-ws-subscription-issue

OP-2481 Fix ws subscription issue
This commit is contained in:
Dmitry
2022-06-30 16:21:39 +03:00
committed by GitHub
3 changed files with 24 additions and 7 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@orionprotocol/sdk",
"version": "0.12.7",
"version": "0.12.8",
"description": "Orion Protocol SDK",
"main": "./lib/esm/index.js",
"module": "./lib/esm/index.js",

View File

@@ -144,6 +144,12 @@ const isSubType = (subType: string): subType is keyof Subscription => Object.val
class OrionAggregatorWS {
private ws: WebSocket | undefined;
// is used to make sure we do not need to renew ws subscription
// we can not be sure that onclose event will recieve our code when we do `ws.close(4000)`
// since sometimes it can be replaced with system one.
// https://stackoverflow.com/questions/19304157/getting-the-reason-why-websockets-closed-with-close-code-1006
private isClosedIntentionally = false;
private subscriptions: Partial<{
[K in keyof Subscription]: Partial<Record<string, Subscription[K]>>
}> = {};
@@ -254,14 +260,16 @@ class OrionAggregatorWS {
}
destroy() {
this.ws?.close(4000);
this.isClosedIntentionally = true;
this.ws?.close();
delete this.ws;
}
init(isReconnect = false) {
this.isClosedIntentionally = false;
this.ws = new WebSocket(this.wsUrl);
this.ws.onclose = (e) => {
if (e.code !== 4000) this.init(true);
this.ws.onclose = () => {
if (!this.isClosedIntentionally) this.init(true);
};
this.ws.onopen = () => {
// Re-subscribe to all subscriptions

View File

@@ -74,6 +74,12 @@ export default class PriceFeedSubscription<T extends SubscriptionType = Subscrip
readonly type: T;
// is used to make sure we do not need to renew ws subscription
// we can not be sure that onclose event will recieve our code when we do `ws.close(4000)`
// since sometimes it can be replaced with system one.
// https://stackoverflow.com/questions/19304157/getting-the-reason-why-websockets-closed-with-close-code-1006
private isClosedIntentionally = false;
constructor(
type: T,
url: string,
@@ -91,6 +97,8 @@ export default class PriceFeedSubscription<T extends SubscriptionType = Subscrip
}
init() {
this.isClosedIntentionally = false;
const { payload, url, type } = this;
this.ws = new WebSocket(`${url}/${type}${payload ? `/${payload.toString()}` : ''}`);
@@ -106,9 +114,9 @@ export default class PriceFeedSubscription<T extends SubscriptionType = Subscrip
this.callback(parseResult.data);
};
this.ws.onclose = (e) => {
this.ws.onclose = () => {
if (this.heartbeatInterval) clearInterval(this.heartbeatInterval);
if (e.code !== 4000) this.init();
if (!this.isClosedIntentionally) this.init();
};
this.heartbeatInterval = setInterval(() => {
@@ -117,6 +125,7 @@ export default class PriceFeedSubscription<T extends SubscriptionType = Subscrip
}
kill() {
this.ws?.close(4000);
this.isClosedIntentionally = true;
this.ws?.close();
}
}