From 870326b8245f16fafde0b0c32cfd2f277946e3a1 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Mon, 14 Sep 2020 11:21:03 -0700 Subject: [PATCH] feat: add initial retry delay, and set default to 100ms (#336) --- README.md | 3 +++ src/common.ts | 3 +-- src/retry.ts | 7 +++++-- test/test.retry.ts | 26 ++++++++++++++++++++++++++ 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8e9aaeca..b43e620e 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/common.ts b/src/common.ts index 258b8383..017fe013 100644 --- a/src/common.ts +++ b/src/common.ts @@ -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; diff --git a/src/retry.ts b/src/retry.ts index 178d4d53..a4462a95 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -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; diff --git a/test/test.retry.ts b/test/test.retry.ts index ee32a34e..4fda2457 100644 --- a/test/test.retry.ts +++ b/test/test.retry.ts @@ -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(); + }); });