From 8917128bd6d10c1ea3b2ad229e4e21acfc656aa0 Mon Sep 17 00:00:00 2001 From: Mauricio Schneider Date: Wed, 4 Nov 2015 12:28:40 -0300 Subject: [PATCH] Change long-polling strategy to 5secs interval strategy on 5+ instant responses. --- .../control-panel/long-polling/index.js | 22 +++++++++++++++++-- lib/agent/providers/network/index.js | 5 ++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/agent/plugins/control-panel/long-polling/index.js b/lib/agent/plugins/control-panel/long-polling/index.js index 697f2008b..360a08f90 100644 --- a/lib/agent/plugins/control-panel/long-polling/index.js +++ b/lib/agent/plugins/control-panel/long-polling/index.js @@ -12,7 +12,8 @@ var emitter, connection_status, connected, current_request, - loaded; + loaded, + instant_responses = 0; var request = function(re_schedule) { if (!connected || current_request) { @@ -29,6 +30,10 @@ var request = function(re_schedule) { device_key = keys.get().device, api_key = keys.get().api; + // used for benchmarking and request interval setup + var request_start, + response_delay; + if (!keys.get().device) return propagate_error(errors.get('NO_DEVICE_KEY')); var base = protocol + '://' + host, @@ -48,6 +53,7 @@ var request = function(re_schedule) { } logger.debug('Fetching instructions...'); + request_start = new Date() current_request = needle.get(url, options); attach_listeners(current_request); @@ -64,7 +70,7 @@ var request = function(re_schedule) { request.on('end', function() { var msg = options.proxy ? 'with proxy' : ''; - logger.debug("Request " + msg + " ended."); + logger.debug('Request ' + msg + ' ended'); }); request.request.on('response', function(res) { @@ -72,6 +78,18 @@ var request = function(re_schedule) { propagate_error('Invalid response received with status code ' + res.statusCode); clear_current_request(); } else { + response_delay = (new Date() - request_start) / 1000; + + if (response_delay < 1) { + instant_responses++ + } else { + instant_responses = 0; + } + + if (instant_responses > 5) { + logger.debug('It seems the server is not using long-polling. Adding delay.'); + return setTimeout(check_for_reschedule, 5000); + } check_for_reschedule(); } }); diff --git a/lib/agent/providers/network/index.js b/lib/agent/providers/network/index.js index 43a0b8274..9cfeb4517 100644 --- a/lib/agent/providers/network/index.js +++ b/lib/agent/providers/network/index.js @@ -150,7 +150,10 @@ exp.get_connection_status = function(cb) { } if (res && res.statusCode) { - if (res.statusCode === 200) { + // 301 and 302 codes are in case the server redirects regular requests, + // but is still able to receive connections + var statusCodes = [200, 301, 302]; + if (statusCodes.indexOf(res.statusCode) !== -1) { return cb('connected'); } else { disconnected();