Skip to content

Commit

Permalink
accept backoff function in retry option
Browse files Browse the repository at this point in the history
Closes #138
  • Loading branch information
floatdrop committed Dec 1, 2015
1 parent 54bd6f5 commit 54eb01b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 9 deletions.
22 changes: 15 additions & 7 deletions index.js
Expand Up @@ -19,11 +19,6 @@ var nodeStatusCodes = require('node-status-codes');
var isPlainObj = require('is-plain-obj');
var parseJson = require('parse-json');

function backoff(iter) {
var noise = Math.random() * 100;
return (1 << iter) * 1000 + noise;
}

function requestAsEventEmitter(opts) {
opts = opts || {};

Expand Down Expand Up @@ -61,8 +56,9 @@ function requestAsEventEmitter(opts) {
});

req.once('error', function (err) {
if (retryCount < opts.retries) {
setTimeout(get, backoff(++retryCount), opts);
var backoff = opts.retries(++retryCount);
if (backoff) {
setTimeout(get, backoff, opts);
return;
}

Expand Down Expand Up @@ -270,6 +266,18 @@ function normalizeArguments(url, opts) {
}
}

if (typeof opts.retries !== 'function') {
var retries = opts.retries;
opts.retries = function backoff(iter) {
if (iter > retries) {
return 0;
}

var noise = Math.random() * 100;
return (1 << iter) * 1000 + noise;
};
}

return opts;
}

Expand Down
5 changes: 3 additions & 2 deletions readme.md
Expand Up @@ -118,11 +118,12 @@ Milliseconds after which the request will be aborted and an error event with `ET

###### retries

Type: `number`
Type: `number`, `function`
Default: `5`

Number of request retries when network errors happens.
Number of request retries when network errors happens. Delays between retries counts with function `Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).

Option accepts `function` that accepts `retry` argument and returns delay in milliseconds. `0` return value cancels retry.

##### callback(error, data, response)

Expand Down
20 changes: 20 additions & 0 deletions test/retry.js
Expand Up @@ -5,6 +5,7 @@ import {createServer} from './_server';
let s;
let trys = 0;
let knocks = 0;
let fifth = 0;

test.before('setup', async t => {
s = await createServer();
Expand All @@ -21,6 +22,12 @@ test.before('setup', async t => {
trys++;
});

s.on('/fifth', (req, res) => {
if (fifth++ === 5) {
res.end('who`s there?');
}
});

await s.listen(s.port);
});

Expand All @@ -38,6 +45,19 @@ test('can be disabled with option', async t => {
t.is(trys, 1);
});

test('funcion gets iter count', async t => {
await got(`${s.url}/fifth`, {timeout: 10, retries: iter => iter < 10});
t.is(fifth, 6);
});

test('falsy value prevent retries', async t => {
try {
await got(`${s.url}/long`, {timeout: 1000, retries: () => 0});
} catch (err) {
t.ok(err);
}
});

test.after('cleanup', async t => {
await s.close();
});

0 comments on commit 54eb01b

Please sign in to comment.