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 simplistic exponential backoff retry #6

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,16 @@ class rpRetry {
logger.info(`Encountered error ${err.message} for ${options.method} request to ${options.uri}, retry count ${tryCount}`);
tryCount -= 1;
if (tryCount) {
return fetchDataWithRetry(tryCount);
let delay = options.delay || 100; // default delay between retries
batmat marked this conversation as resolved.
Show resolved Hide resolved
if (options.factor) {
delay *= options.factor;
}
return new Promise((resolve, reject) => {
setTimeout(() => {
logger.debug(`waiting for ${delay} ms before next retry for ${options.uri}`);
resolve(fetchDataWithRetry(tryCount));
}, delay);
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider multiplying the delay by the factor after the fetch.

On might expect the second request to happen 100 ms after the first request, but currently it's 100 ms * factor instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@markstos nope, this is in the catch clause. So as I understand it, this is already on the first failure. I did have the same thought as you are, and agree waiting on the first download would be wasteful :-).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah sorry, I didn't read enough code context. Well done.

}
return Promise.reject(err);
});
Expand Down
14 changes: 14 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,18 @@ describe('request-promise-retry', function () {
expect(data.error).equal(undefined);
});
});
it('should pass, retry with exponential backoff', () => {
// failure should take a bit of time to happen
const startTime = new Date();
return rp({
uri: 'http://adadadadad.com/',
method: 'GET',
retry: 5,
delay: 200,
factor: 1.1 //
})
.catch(error => {
expect(new Date() - startTime).to.be.above((5 - 1) * 200);
});
});
});