0

Handle websocket errors and reconnection. Closes #1869

This commit is contained in:
Gabe Kangas 2022-10-18 16:39:49 -07:00
parent cc94bdeda0
commit 3e89937d2b
No known key found for this signature in database
GPG Key ID: 9A56337728BC81EA
2 changed files with 29 additions and 14 deletions

View File

@ -68,6 +68,7 @@ export const chatAuthenticatedAtom = atom<boolean>({
export const websocketServiceAtom = atom<WebsocketService>({
key: 'websocketServiceAtom',
default: null,
dangerouslyAllowMutability: true,
});
export const appStateAtom = atom<AppStateOptions>({

View File

@ -14,24 +14,24 @@ export default class WebsocketService {
websocketReconnectTimer: ReturnType<typeof setTimeout>;
isShutdown = false;
backOff = 1000;
handleMessage?: (message: SocketEvent) => void;
constructor(accessToken, path) {
this.accessToken = accessToken;
this.path = path;
// this.websocketReconnectTimer = null;
// this.accessToken = accessToken;
// this.websocketConnectedListeners = [];
// this.websocketDisconnectListeners = [];
// this.rawMessageListeners = [];
this.websocketReconnectTimer = null;
// this.send = this.send.bind(this);
// this.createAndConnect = this.createAndConnect.bind(this);
this.createAndConnect = this.createAndConnect.bind(this);
// this.scheduleReconnect = this.scheduleReconnect.bind(this);
// this.shutdown = this.shutdown.bind(this);
// this.onError = this.onError.bind(this);
this.shutdown = this.shutdown.bind(this);
// this.isShutdown = false;
this.isShutdown = false;
this.createAndConnect();
}
@ -46,7 +46,6 @@ export default class WebsocketService {
console.debug('connecting to ', url.toString());
const ws = new WebSocket(url.toString());
ws.onopen = this.onOpen.bind(this);
// ws.onclose = this.onClose.bind(this);
ws.onerror = this.onError.bind(this);
ws.onmessage = this.onMessage.bind(this);
@ -61,12 +60,27 @@ export default class WebsocketService {
// On ws error just close the socket and let it re-connect again for now.
onError(e) {
console.error(e);
handleNetworkingError(`Socket error: ${e}`);
this.websocket.close();
// if (!this.isShutdown) {
// this.scheduleReconnect();
// }
if (!this.isShutdown) {
this.scheduleReconnect();
}
}
scheduleReconnect() {
if (this.websocketReconnectTimer) {
clearTimeout(this.websocketReconnectTimer);
}
this.backOff *= 2;
this.websocketReconnectTimer = setTimeout(
this.createAndConnect,
5000 + Math.min(this.backOff, 10_000),
);
}
shutdown() {
this.isShutdown = true;
this.websocket.close();
}
/*