Skip to content

Commit

Permalink
fix(SocketStore): improve socket error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
iGroza committed Nov 20, 2024
1 parent 8fa56ca commit 8779244
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 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,13 @@ class SocketStore {
}
this.fallbackIntervalTimer = setInterval(() => {
Wallet.fetchBalances();
}, 6000);
}, FALLBACK_INTERVAL_MS);
};

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

attach = (url?: string) => {
Expand Down Expand Up @@ -73,28 +83,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 +150,7 @@ class SocketStore {
try {
this.instance?.send(message);
} catch (err) {
//
logger.error('ping error: ', err);
}
}
},
Expand Down

0 comments on commit 8779244

Please sign in to comment.