Skip to content

Commit

Permalink
feat: add initial retry delay, and set default to 100ms (#336)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith authored Sep 14, 2020
1 parent 8b626d4 commit 870326b
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 4 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ gaxios.request({url: '/data'}).then(...);

// When there is no response, the number of retries to attempt. Defaults to 2.
noResponseRetries?: number;

// The amount of time to initially delay the retry, in ms. Defaults to 100ms.
retryDelay?: number;
},

// Enables default configuration for retries.
Expand Down
3 changes: 1 addition & 2 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,7 @@ export interface RetryConfig {
currentRetryAttempt?: number;

/**
* The amount of time to initially delay the retry. Defaults to 100.
* @deprecated
* The amount of time to initially delay the retry, in ms. Defaults to 100ms.
*/
retryDelay?: number;

Expand Down
7 changes: 5 additions & 2 deletions src/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@ export async function getRetryConfig(err: GaxiosError) {
}

// Calculate time to wait with exponential backoff.
// Formula: (2^c - 1 / 2) * 1000
const delay = ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000;
// If this is the first retry, look for a configured retryDelay.
const retryDelay = config.currentRetryAttempt ? 0 : config.retryDelay ?? 100;
// Formula: retryDelay + ((2^c - 1 / 2) * 1000)
const delay =
retryDelay + ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000;

// We're going to retry! Incremenent the counter.
err.config.retryConfig!.currentRetryAttempt! += 1;
Expand Down
26 changes: 26 additions & 0 deletions test/test.retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,30 @@ describe('🛸 retry & exponential backoff', () => {
});
scope.done();
});

it('should delay the initial retry by 100ms by default', async () => {
const scope = nock(url).get('/').reply(500).get('/').reply(200, {});
const start = Date.now();
await request({
url,
retry: true,
});
const delay = Date.now() - start;
assert.ok(delay > 100 && delay < 150);
scope.done();
});

it('should respect the retryDelay if configured', async () => {
const scope = nock(url).get('/').reply(500).get('/').reply(200, {});
const start = Date.now();
await request({
url,
retryConfig: {
retryDelay: 500,
},
});
const delay = Date.now() - start;
assert.ok(delay > 500 && delay < 550);
scope.done();
});
});

0 comments on commit 870326b

Please sign in to comment.