diff --git a/src/lib/cloud-provider.js b/src/lib/cloud-provider.js index 1e6fb2adeca3635939aa9bf7c0e987bb2363ece2..421dd01168400ab9196ae7a2f0a1039188ec1e2b 100644 --- a/src/lib/cloud-provider.js +++ b/src/lib/cloud-provider.js @@ -65,17 +65,19 @@ class CloudProvider { onClose () { log.info(`Closed connection to websocket`); - const exponentialTimeout = (Math.pow(2, this.connectionAttempts) - 1) * 1000; - const randomizedTimeout = this.randomizeDuration(exponentialTimeout); + const randomizedTimeout = this.randomizeDuration(this.exponentialTimeout()); this.setTimeout(this.reconnectNow.bind(this), randomizedTimeout); } reconnectNow () { - // Max connection attempts at 5, so timeout will max out in range [0, 31s] - this.connectionAttempts = Math.min(this.connectionAttempts + 1, 5); + this.connectionAttempts = this.connectionAttempts + 1; this.openConnection(); } + exponentialTimeout () { + return (Math.pow(2, Math.min(this.connectionAttempts, 5)) - 1) * 1000; + } + randomizeDuration (t) { return Math.random() * t; } @@ -168,6 +170,7 @@ class CloudProvider { if (this.connection && this.connection.readyState !== WebSocket.CLOSING && this.connection.readyState !== WebSocket.CLOSED) { + log.info('Request close cloud connection without reconnecting'); this.connection.onclose = () => {}; // Remove close listener to prevent reconnect this.connection.close(); } diff --git a/test/unit/util/cloud-provider.test.js b/test/unit/util/cloud-provider.test.js index d5f8a711222f7e3034a3069bca05a3a1fd47557f..3ef4179d22a9e2588196b346f5be8b060a51d69e 100644 --- a/test/unit/util/cloud-provider.test.js +++ b/test/unit/util/cloud-provider.test.js @@ -141,12 +141,17 @@ describe('CloudProvider', () => { cloudProvider.connection.close(); expect(timeout).toEqual(31 * 1000); // 2^5 - 1 expect(websocketConstructorCount).toBe(6); - expect(cloudProvider.connectionAttempts).toBe(5); // Maxed at 5 + expect(cloudProvider.connectionAttempts).toBe(6); cloudProvider.connection.close(); expect(timeout).toEqual(31 * 1000); // maxed out at 2^5 - 1 expect(websocketConstructorCount).toBe(7); - expect(cloudProvider.connectionAttempts).toBe(5); // Maxed at 5 + expect(cloudProvider.connectionAttempts).toBe(7); + }); + + test('exponentialTimeout caps connection attempt number', () => { + cloudProvider.connectionAttempts = 1000; + expect(cloudProvider.exponentialTimeout()).toEqual(31 * 1000); }); test('requestCloseConnection does not try to reconnect', () => {