Skip to content

There can be more than Notion and Miro. AFFiNE(pronounced [ə‘fain]) is a next-gen knowledge base that brings planning, sorting and creating all together. Privacy first, open-source, customizable and ready to use.

fix: fix reconnect logic (#730)

MingLiang Wangc95667eafbe7
diff --git a/packages/data-center/src/provider/affine/channel.ts b/packages/data-center/src/provider/affine/channel.ts
index 1503a8b450..da9e81c35e 100644
--- a/packages/data-center/src/provider/affine/channel.ts
+++ b/packages/data-center/src/provider/affine/channel.ts
@@ -3,13 +3,13 @@ import { Logger } from 'src/types';
import { token } from './apis/token';
import * as url from 'lib0/url';
-const RECONNECT_INTERVAL_TIME = 5000;
+const RECONNECT_INTERVAL_TIME = 500;
const MAX_RECONNECT_TIMES = 50;
export class WebsocketClient extends websocket.WebsocketClient {
public shouldReconnect = false;
- private _reconnectInterval: number | null = null;
private _logger: Logger;
+ private _retryTimes = 0;
constructor(
serverUrl: string,
logger: Logger,
@@ -34,30 +34,28 @@ export class WebsocketClient extends websocket.WebsocketClient {
this.on('connect', () => {
this._logger('Affine channel connected');
this.shouldReconnect = true;
- if (this._reconnectInterval) {
- window.clearInterval(this._reconnectInterval);
- }
+ this._retryTimes = 0;
});
this.on('disconnect', ({ error }: { error: Error }) => {
if (error) {
- let times = 0;
// Try reconnect if connect error has occurred
- this._reconnectInterval = window.setInterval(() => {
- if (this.shouldReconnect && token.isLogin && !this.connected) {
- try {
- this.connect();
- this._logger(`try reconnect channel ${++times} times`);
- if (times > MAX_RECONNECT_TIMES) {
+ if (this.shouldReconnect && token.isLogin && !this.connected) {
+ try {
+ setTimeout(() => {
+ if (this._retryTimes <= MAX_RECONNECT_TIMES) {
+ this.connect();
+ this._logger(
+ `try reconnect channel ${++this._retryTimes} times`
+ );
+ } else {
this._logger('reconnect failed, max reconnect times reached');
- this._reconnectInterval &&
- window.clearInterval(this._reconnectInterval);
}
- } catch (e) {
- this._logger('reconnect failed', e);
- }
+ }, RECONNECT_INTERVAL_TIME);
+ } catch (e) {
+ this._logger('reconnect failed', e);
}
- }, RECONNECT_INTERVAL_TIME);
+ }
}
});
}