From ec303c95c93ccafe4e7fd791207c82c83c4e1ab4 Mon Sep 17 00:00:00 2001 From: Felipe Trost Date: Thu, 17 Apr 2025 15:17:18 +0200 Subject: [PATCH 1/2] exponential backoff for ws reconnection --- src/snapcontrol.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/snapcontrol.ts b/src/snapcontrol.ts index fea3ff6..28a01d3 100644 --- a/src/snapcontrol.ts +++ b/src/snapcontrol.ts @@ -261,6 +261,7 @@ class SnapControl { this.msg_id = 0; this.status_req_id = -1; this.timer = null; + this.reconnection_attempts = 0; } public connect(baseUrl: string) { @@ -269,6 +270,7 @@ class SnapControl { this.connection = new WebSocket(baseUrl + '/jsonrpc'); this.connection.onmessage = (msg: MessageEvent) => this.onMessage(msg.data); this.connection.onopen = () => { + this.reconnection_attempts = 0; this.status_req_id = this.sendRequest('Server.GetStatus'); if (this.onConnectionChanged) this.onConnectionChanged(this, true); @@ -277,17 +279,22 @@ class SnapControl { this.connection.onclose = () => { if (this.onConnectionChanged) this.onConnectionChanged(this, false, 'Connection lost, trying to reconnect.'); - console.info('connection lost, reconnecting in 1s'); - this.timer = setTimeout(() => this.connect(baseUrl), 1000); + const reconnectionDelay = this.getReconnectDelay(); + this.timer = setTimeout(() => this.connect(baseUrl), reconnectionDelay * 1000); }; } catch (e) { - console.info('Exception while connecting: "' + e + '", reconnecting in 1s'); + const reconnectionDelay = this.getReconnectDelay(); + console.info('Exception while connecting: "' + e + '", reconnecting in ' + reconnectionDelay + 's'); if (this.onConnectionChanged) this.onConnectionChanged(this, false, 'Exception while connecting: "' + e + '", trying to reconnect.'); - this.timer = setTimeout(() => this.connect(baseUrl), 1000); + this.timer = setTimeout(() => this.connect(baseUrl), reconnectionDelay * 1000); } } + private getReconnectDelay() { + return 1.2 ** this.reconnection_attempts++ - 1; + } + public disconnect() { if (this.timer) clearTimeout(this.timer); @@ -298,6 +305,7 @@ class SnapControl { } } if (this.onConnectionChanged) + this.onConnectionChanged(this, false); } @@ -532,6 +540,7 @@ class SnapControl { msg_id: number; status_req_id: number; timer: ReturnType | null; + reconnection_attempts: number } From 0b11c85a15daab02fd03ebf7ebfd031dba3ea9cc Mon Sep 17 00:00:00 2001 From: Felipe Trost Date: Thu, 17 Apr 2025 18:00:05 +0200 Subject: [PATCH 2/2] slower backoff + max 1s backoff --- src/snapcontrol.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/snapcontrol.ts b/src/snapcontrol.ts index 28a01d3..8f64198 100644 --- a/src/snapcontrol.ts +++ b/src/snapcontrol.ts @@ -292,7 +292,7 @@ class SnapControl { } private getReconnectDelay() { - return 1.2 ** this.reconnection_attempts++ - 1; + return Math.min(1.1 ** this.reconnection_attempts++ - 1, 1); } public disconnect() {