Skip to content

Commit

Permalink
Give some servers a bit more time to recover from a 502 response when…
Browse files Browse the repository at this point in the history
… requesting HEAD + GET in close succession. Avoids 502 response to GET request. Fixes #120
  • Loading branch information
Munter committed Jul 16, 2017
1 parent 27537f7 commit 1b2c80c
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,12 @@ module.exports = function (options) {
}
}

function httpStatus(url, relations, retryWithGetMethod) {
function httpStatus(url, relations, attempt) {
attempt = attempt || 1;

return function (callback) {
request({
method: retryWithGetMethod ? 'get' : 'head',
method: attempt === 1 ? 'head' : 'get',
url: url.replace(/#.*$/, ''),
strictSSL: true,
gzip: true,
Expand All @@ -170,8 +172,8 @@ module.exports = function (options) {

if (code) {
// Some servers send responses that request apparently handles badly when using the HEAD method...
if (code === 'HPE_INVALID_CONSTANT' && !retryWithGetMethod) {
return httpStatus(url, relations, true)(callback);
if (code === 'HPE_INVALID_CONSTANT' && attempt === 1) {
return httpStatus(url, relations, attempt + 1)(callback);
}

if (code === 'ENOTFOUND') {
Expand All @@ -187,8 +189,17 @@ module.exports = function (options) {

callback(undefined, status);
} else {
if (!retryWithGetMethod && res.statusCode >= 400 && res.statusCode < 500) {
return httpStatus(url, relations, true)(callback);
// Some servers respond weirdly to HEAD requests. Make a second attempt with GET
if (attempt === 1 && res.statusCode >= 400 && res.statusCode < 600) {
return httpStatus(url, relations, attempt + 1)(callback);
}

// Some servers (jspm.io) respond with 502 if requesting HEAD, then GET to close in succession. Give the server a second to cool down
if (attempt === 2 && res.statusCode >= 400 && res.statusCode < 600) {
setTimeout(function () {
httpStatus(url, relations, attempt + 1)(callback);
}, 1000);
return;
}

status = res.statusCode;
Expand Down

0 comments on commit 1b2c80c

Please sign in to comment.