Skip to content

Commit

Permalink
Add noise retry option
Browse files Browse the repository at this point in the history
Fixes #1690
  • Loading branch information
szmarczak committed Apr 26, 2021
1 parent 1435985 commit e830077
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 2 deletions.
2 changes: 1 addition & 1 deletion source/core/calculate-retry-delay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const calculateRetryDelay: Returns<RetryFunction, number> = ({
}
}

const noise = Math.random() * 100;
const noise = Math.random() * retryOptions.noise;
return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise;
};

Expand Down
9 changes: 8 additions & 1 deletion source/core/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ export interface RetryOptions {
errorCodes: string[];
calculateDelay: RetryFunction;
backoffLimit: number;
noise: number;
maxRetryAfter?: number;
}

Expand Down Expand Up @@ -618,7 +619,8 @@ const defaultInternals: Options['_internals'] = {
],
maxRetryAfter: undefined,
calculateDelay: ({computedValue}) => computedValue,
backoffLimit: Number.POSITIVE_INFINITY
backoffLimit: Number.POSITIVE_INFINITY,
noise: 100
},
localAddress: undefined,
method: 'GET',
Expand Down Expand Up @@ -1785,6 +1787,11 @@ export default class Options {
assert.any([is.array, is.undefined], value.methods);
assert.any([is.array, is.undefined], value.statusCodes);
assert.any([is.array, is.undefined], value.errorCodes);
assert.any([is.number, is.undefined], value.noise);

if (value.noise && Math.abs(value.noise) > 100) {
throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`);
}

for (const key in value) {
if (!(key in this._internals.retry)) {
Expand Down
50 changes: 50 additions & 0 deletions test/arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,3 +557,53 @@ test('prefixUrl is properly replaced when extending', withServer, async (t, serv

t.is(await child.get('').text(), '/other/path/');
});

test('throws on too large noise', t => {
t.throws(() => {
new Options({
retry: {
noise: 101
}
});
}, {
message: 'The maximum acceptable retry noise is +/- 100ms, got 101'
});

t.throws(() => {
new Options({
retry: {
noise: -101
}
});
}, {
message: 'The maximum acceptable retry noise is +/- 100ms, got -101'
});

t.throws(() => {
new Options({
retry: {
noise: Number.POSITIVE_INFINITY
}
});
}, {
message: 'The maximum acceptable retry noise is +/- 100ms, got Infinity'
});

t.throws(() => {
new Options({
retry: {
noise: Number.NEGATIVE_INFINITY
}
});
}, {
message: 'The maximum acceptable retry noise is +/- 100ms, got -Infinity'
});

t.notThrows(() => {
new Options({
retry: {
noise: 0
}
});
});
});

0 comments on commit e830077

Please sign in to comment.