From a0f773aa3cac547ff071af823276b921a35b4f99 Mon Sep 17 00:00:00 2001
From: Rhys Arkins <rhys@keylocation.sg>
Date: Fri, 20 Oct 2017 06:24:09 +0200
Subject: [PATCH] feat: retry github 401 bad credentials responses (#1000)

Closes #996
---
 lib/api/gh-got-wrapper.js       | 23 ++++++++++++++++++-----
 test/api/gh-got-wrapper.spec.js |  6 ++++++
 2 files changed, 24 insertions(+), 5 deletions(-)

diff --git a/lib/api/gh-got-wrapper.js b/lib/api/gh-got-wrapper.js
index 89018d6d75..fba2978673 100644
--- a/lib/api/gh-got-wrapper.js
+++ b/lib/api/gh-got-wrapper.js
@@ -48,8 +48,7 @@ async function get(path, opts, retries = 5) {
         await sleep(5000 / retries);
       }
       return get(path, opts, retries - 1);
-    }
-    if (
+    } else if (
       retries > 0 &&
       err.statusCode === 403 &&
       err.message &&
@@ -65,8 +64,7 @@ async function get(path, opts, retries = 5) {
         await sleep(180000 / (retries * retries));
       }
       return get(path, opts, retries - 1);
-    }
-    if (
+    } else if (
       err.statusCode === 403 &&
       err.message &&
       err.message.indexOf('rate limit exceeded') !== -1
@@ -82,7 +80,22 @@ async function get(path, opts, retries = 5) {
         }
         return get(path, opts, retries - 1);
       }
-      logger.info({ headers: err.headers }, 'Failed retrying request');
+    } else if (
+      err.statusCode === 401 &&
+      err.message &&
+      err.message.indexOf('Bad credentials') !== -1
+    ) {
+      if (retries > 0) {
+        logger.info(
+          { statusCode: err.statusCode, message: err.message },
+          `Retrying request`
+        );
+        // istanbul ignore if
+        if (process.env.NODE_ENV !== 'test') {
+          await sleep(5000 / retries);
+        }
+        return get(path, opts, retries - 1);
+      }
     }
     throw err;
   }
diff --git a/test/api/gh-got-wrapper.spec.js b/test/api/gh-got-wrapper.spec.js
index ef738176f8..adf439a933 100644
--- a/test/api/gh-got-wrapper.spec.js
+++ b/test/api/gh-got-wrapper.spec.js
@@ -97,6 +97,12 @@ describe('api/gh-got-wrapper', () => {
         message: 'API rate limit exceeded for x.',
       })
     );
+    ghGot.mockImplementationOnce(() =>
+      Promise.reject({
+        statusCode: 401,
+        message: 'Bad credentials',
+      })
+    );
     ghGot.mockImplementationOnce(() =>
       Promise.reject({
         statusCode: 403,
-- 
GitLab