From 17911d43fcd4125c5ccf32e12bb710d848051deb Mon Sep 17 00:00:00 2001 From: Calvin Montgomery Date: Thu, 21 Jun 2018 22:05:20 -0700 Subject: [PATCH] Start working on reconnect logic --- www/js/util.js | 6 +++++- www/js/ws.js | 41 +++++++++++++++++++++++++++++++++++------ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/www/js/util.js b/www/js/util.js index 2729e863..5f2ed1bb 100644 --- a/www/js/util.js +++ b/www/js/util.js @@ -3305,6 +3305,7 @@ function backoffRetry(fn, cb, options) { var jitter = options.jitter || 0; var factor = options.factor || 1; var isRetryable = options.isRetryable || function () { return true; }; + var maxDelay = options.maxDelay || Infinity; var tries = 0; function callback(error, result) { @@ -3316,7 +3317,10 @@ function backoffRetry(fn, cb, options) { cb(error, result); } else if (isRetryable(error)) { var offset = Math.random() * jitter; - var delay = options.delay * factor + offset; + var delay = Math.min( + options.delay * factor, + maxDelay + ) + offset; console.log('Retrying on error: ' + error); console.log('Waiting ' + delay + ' ms before retrying'); diff --git a/www/js/ws.js b/www/js/ws.js index f737029c..52d40528 100644 --- a/www/js/ws.js +++ b/www/js/ws.js @@ -5,10 +5,11 @@ function WSShim(ws) { this._ws = ws; this._listeners = Object.create(null); + this._connected = false; + this._ws.onopen = this._onopen.bind(this); this._ws.onclose = this._onclose.bind(this); this._ws.onmessage = this._onmessage.bind(this); - this._ws.onerror = this._onerror.bind(this); this._ackId = 0; this._pendingAcks = Object.create(null); @@ -51,9 +52,41 @@ }); }; + WSShim.prototype._onopen = function _onopen() { + this._connected = true; + }; + WSShim.prototype._onclose = function _onclose() { - // TODO: reconnect logic + if (!this._connected) { + return; + } + this._emit('disconnect'); + + if (!KICKED) { + function reconnectAsync(cb) { + initWS(); + + window.socket._ws.addEventListener('open', function () { + cb(null); + }); + + window.socket._ws.addEventListener('error', function (error) { + cb(error); + }); + } + + var retryOpts = { + delay: 1000, + jitter: 1000, + factor: 2, + maxDelay: 20000 + }; + + setTimeout(function () { + backoffRetry(reconnectAsync, function(){}, retryOpts); + }, 1000); + } }; WSShim.prototype._onmessage = function _onmessage(message) { @@ -78,9 +111,5 @@ } }; - WSShim.prototype._onerror = function _onerror() { - console.error('Dunno how to handle onerror'); - }; - window.WSShim = WSShim; })();