diff --git a/lib/policies/proxy/proxy.js b/lib/policies/proxy/proxy.js index abb5254f2..ed4abf5d8 100644 --- a/lib/policies/proxy/proxy.js +++ b/lib/policies/proxy/proxy.js @@ -61,11 +61,26 @@ module.exports = function (params, config) { proxyOptions.agent = new ProxyAgent(intermediateProxyUrl); } + const retryCountMap = {}; const proxy = httpProxy.createProxyServer(Object.assign(params, proxyOptions)); + proxy.on('end', (req, res) => { + delete retryCountMap[req.egContext.requestID]; + }); + // retry function + const maxAutoRetries = params.maxAutoRetries || 1; proxy.on('error', (err, req, res) => { logger.warn(err); + const requestID = req.egContext.requestID; + let retryCount = retryCountMap[requestID] || 0; + if (retryCount < maxAutoRetries) { + retryCount++; + retryCountMap[requestID] = retryCount; + proxyHandler(req, res); + return; + } + delete retryCountMap[requestID]; if (!res.headersSent) { res.status(502).send('Bad gateway.'); } else { @@ -100,10 +115,9 @@ module.exports = function (params, config) { } } : () => { }; - return function proxyHandler(req, res) { + function proxyHandler(req, res) { const target = balancer.nextTarget(); const headers = Object.assign({ 'eg-request-id': req.egContext.requestID }, proxyOptions.headers); - stripPathFn(req); logger.debug(`proxying to ${target.href}, ${req.method} ${req.url}`); @@ -115,6 +129,7 @@ module.exports = function (params, config) { agent: !intermediateProxyUrl ? target.protocol === 'https:' ? httpsAgent : httpAgent : proxyOptions.agent }); }; + return proxyHandler; // multiple urls will load balance, defaulting to round-robin };