From cd164c67b5164f9e78e4777502819193f67efce8 Mon Sep 17 00:00:00 2001
From: Xiao Gui <xgui3783@gmail.com>
Date: Thu, 9 Apr 2020 12:53:08 +0200
Subject: [PATCH] bugfix: retries on failed saneUrl set

---
 deploy/saneUrl/store.js      | 14 +++++++++++++-
 deploy/saneUrl/store.spec.js | 18 ++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/deploy/saneUrl/store.js b/deploy/saneUrl/store.js
index 1cb6cb8db..9765a6181 100644
--- a/deploy/saneUrl/store.js
+++ b/deploy/saneUrl/store.js
@@ -43,6 +43,7 @@ class Store {
 
   async getToken() {
     this.token = await this.wrapper.getScopedToken({ projectId: OBJ_STORAGE_PROJECT_ID })
+    return this.token
   }
 
   get(id) {
@@ -60,7 +61,7 @@ class Store {
     })
   }
 
-  set(id, value) {
+  _set(id, value) {
     return new Promise((rs, rj) => {
       request.put(`${this.objStorateRootUrl}/${id}`, {
         headers: {
@@ -75,6 +76,17 @@ class Store {
     })
   }
 
+  async set(id, value) {
+    try {
+      const result = await this._set(id, value)
+      return result
+    } catch (e) {
+      await this.getToken()
+      const result = await this._set(id, value)
+      return result
+    }
+  }
+
   async healthCheck(){
 
   }
diff --git a/deploy/saneUrl/store.spec.js b/deploy/saneUrl/store.spec.js
index 32ce7c043..fc9a37eba 100644
--- a/deploy/saneUrl/store.spec.js
+++ b/deploy/saneUrl/store.spec.js
@@ -28,6 +28,10 @@ describe('> store.js', () => {
       expect(token).to.equal(fakeToken)
     })
 
+    it('> spy gets reset', async () => {
+      expect(getTokenSpy.notCalled).to.be.true
+    })
+
     it('> get works', async () => {
       const scope = nock(objStorateRootUrl)
         .get(`/${objName}`)
@@ -50,8 +54,22 @@ describe('> store.js', () => {
       })
 
       await store.set(objName, objContent)
+      expect(scope.isDone()).to.be.true
+    })
+
+    it('> set retries if at first fails', async () => {
+      let index = 0
+      const scope = nock(objStorateRootUrl)
+        .put(`/${objName}`)
+        .twice()
+        .reply((_uri, _reqBody, cb) => {
+          cb(null, [ index % 2 === 0 ? 401 : 200 ])
+          index ++
+        })
       
+      await store.set(objName, objContent)
       expect(scope.isDone()).to.be.true
+      expect(getTokenSpy.called).to.be.true
     })
   })
 })
-- 
GitLab