From f66711ddf87ea705a972a860d7ebfb6e0d003c6b Mon Sep 17 00:00:00 2001 From: Tyler Date: Mon, 15 Apr 2024 18:04:08 +0900 Subject: [PATCH] fix: implement exponential back off on the retries of `_refreshAccessToken` method (#869) ## What kind of change does this PR introduce? Currently the retry interval of `_refreshAccessToken` goes 200, 400, 600, 800, where as I believe the intended intervals are 200, 400, 800, 1600... ## What is the current behavior? The retry interval is multiple of 200 ms. ## What is the new behavior? The retry interval is properly set exponentially. --------- Co-authored-by: Kang Ming --- src/GoTrueClient.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/GoTrueClient.ts b/src/GoTrueClient.ts index 888704219..5b9e7d367 100644 --- a/src/GoTrueClient.ts +++ b/src/GoTrueClient.ts @@ -1817,7 +1817,9 @@ export default class GoTrueClient { // will attempt to refresh the token with exponential backoff return await retryable( async (attempt) => { - await sleep(attempt * 200) // 0, 200, 400, 800, ... + if (attempt > 0) { + await sleep(200 * Math.pow(2, attempt - 1)) // 200, 400, 800, ... + } this._debug(debugName, 'refreshing attempt', attempt) @@ -1827,12 +1829,15 @@ export default class GoTrueClient { xform: _sessionResponse, }) }, - (attempt, _, result) => - result && - result.error && - isAuthRetryableFetchError(result.error) && - // retryable only if the request can be sent before the backoff overflows the tick duration - Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION + (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt) + return ( + error && + isAuthRetryableFetchError(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION + ) + } ) } catch (error) { this._debug(debugName, 'error', error)