Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change long-polling strategy to 5secs interval strategy on 5+ instant responses #166

Merged
merged 1 commit into from
Nov 4, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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