Skip to content

Commit

Permalink
Change long-polling strategy to 5secs interval strategy on 5+ instant…
Browse files Browse the repository at this point in the history
… responses.
  • Loading branch information
mauricioschneider committed Nov 4, 2015
1 parent 810d1dd commit 8917128
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
22 changes: 20 additions & 2 deletions lib/agent/plugins/control-panel/long-polling/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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,
Expand All @@ -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);

Expand All @@ -64,14 +70,26 @@ 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) {
if (res.statusCode !== 200) {
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();
}
});
Expand Down
5 changes: 4 additions & 1 deletion lib/agent/providers/network/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 8917128

Please sign in to comment.