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

Add retry mechanism #1068

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
21 changes: 19 additions & 2 deletions lib/policies/proxy/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,28 @@ module.exports = function (params, config) {
proxyOptions.agent = new ProxyAgent(intermediateProxyUrl);
}

const retryCountMap = {};
const proxy = httpProxy.createProxyServer(Object.assign(params, proxyOptions));
// when http request suucess,clear map
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;
// console.log(`retry count: ${retryCount} `, req.originalUrl);
proxyHandler(req, res);
return;
}
delete retryCountMap[requestID];
if (!res.headersSent) {
res.status(502).send('Bad gateway.');
} else {
Expand Down Expand Up @@ -100,10 +117,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}`);
Expand All @@ -115,6 +131,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
};
Expand Down