Skip to content

Commit

Permalink
fix(SocketStore): improve socket error handling (#2213)
Browse files Browse the repository at this point in the history
  • Loading branch information
iGroza authored and devkudasov committed Nov 26, 2024
1 parent d9b9e6b commit af23d66
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions src/models/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import {Wallet} from '@app/models/wallet';
import {RPCMessage} from '@app/types/rpc';

const HEARTBEAT_INTERVAL_MS = 10_000;
const FALLBACK_INTERVAL_MS = 6_000;
const SOCKET_RECONECT_TIMER_MS = 5_000;

const logger = Logger.create('SocketStore', {stringifyJson: true});

class SocketStore {
private instance: WebSocket | null = null;
Expand Down Expand Up @@ -43,7 +47,14 @@ class SocketStore {
}
this.fallbackIntervalTimer = setInterval(() => {
Wallet.fetchBalances();
}, 6000);
}, FALLBACK_INTERVAL_MS);
};

private stopFallbackFetch = () => {
if (this.fallbackIntervalTimer) {
clearInterval(this.fallbackIntervalTimer);
this.fallbackIntervalTimer = null;
}
};

attach = (url?: string) => {
Expand Down Expand Up @@ -73,28 +84,31 @@ class SocketStore {
});
};

this.instance.onerror = e => {
Logger.log('Socket.onError', e.message);
this.detach();
this.fallbackToFetch();
};
const reconnect = (event?: WebSocketErrorEvent | WebSocketCloseEvent) => {
logger.error('reconnecting: ', event);

this.instance.onclose = () => {
this.detach();
this.attach();
setTimeout(() => {
this.attach(url);
}, SOCKET_RECONECT_TIMER_MS);
};

this.instance.onerror = reconnect;
this.instance.onclose = reconnect;
};

detach = () => {
if (!this.instance) {
return;
}
this.stopHeartbeat();
this.stopFallbackFetch();

try {
this.instance.close();
} catch (err) {
if (err instanceof Error) {
Logger.log('Socket.detach error: ', err.message);
logger.error('detach error: ', err.message);
}
}
this.instance = null;
Expand Down Expand Up @@ -137,7 +151,7 @@ class SocketStore {
try {
this.instance?.send(message);
} catch (err) {
//
logger.error('ping error: ', err);
}
}
},
Expand Down

0 comments on commit af23d66

Please sign in to comment.