2017-08-28 53 views
0

我有一個簡單的雲端函數,它接收一個webhook,然後在BigQuery中執行一個流式插入。該代碼是基於這個sample(除了我使用流插入)Cloud Functions中的間歇性身份驗證錯誤

exports.webHook = function webHook (req, res) { 
    return Promise.resolve() 
    .then(() => { 
     if (req.method !== 'POST') { 
     const error = new Error('Only POST requests are accepted'); 
     error.code = 405; 
     throw error; 
     } 

     const events = req.body || {}; 
     if (events) { 
     const opts = { ignoreUnknownValues: true }; 
     bigquery 
      .dataset('config.DATASET') 
      .table('config.TABLE') 
      .insert(events, opts) 
      .then((data) => { 
      console.log(`Success: ${JSON.stringify(data[0])}`); 
      }) 
      .catch((error) => { 
      if (error.name === 'PartialFailureError') { 
       console.error(`PARTIAL ERROR: ${JSON.stringify(error)}`); 
       } else { 
       console.error(`OTHER ERROR: ${JSON.stringify(error)}`); 
      } 

      }); 
     }; 
    }) 
    .then(() => res.status(200).end()) 
    .catch((err) => { 
     console.error(err); 
     res.status(err.code || 500).send(err); 
     return Promise.reject(err); 
    }); 
}; 

此功能以及大部分的時間,但我得到偶爾的身份驗證錯誤,然後消失。 enter image description here

textPayload: "OTHER ERROR: {"code":401,"errors":[{"message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project .","domain":"global","reason":"unauthorized"}],"message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project ."}"

我不知道權威性如何能成爲一個問題,因爲雲計算功能和BigQuery的都是在同一個項目。

+0

我強烈建議彙報[公開問題追蹤]這個問題(https://cloud.google.com/support/docs/問題跟蹤器)。 – Kenworth

+0

你多久會遇到這個錯誤?這可能是因爲你的令牌過期了。 – Sonya

+0

@Sonya - 問題來了,隨機時間消失,我不能指出任何具體的事情。由於雲功能和BigQuery等其他服務都在單個GCP項目中運行,因此應該處理auth。 –

回答

1

Cloud Functions團隊的員工認爲這可能是由於訪問令牌生存時間(TTL)問題引起的,並提出了一種適用於我的解決方法。不要在代碼頂部初始化BigQuery(因爲它們的所有示例都有),請將初始化代碼放在調用函數的內部。

這樣做:代替

exports.webHook = function webHook (req, res) { 
    const bigquery = require('@google-cloud/bigquery')(); 
    return Promise.resolve() 
    .then(() => { 
     if (req.method !== 'POST') { 
     const error = new Error('Only POST requests are accepted'); 
     error.code = 405; 
     throw error; 
     } 
     . 
     . 

const bigquery = require('@google-cloud/bigquery')(); 
. 
. 
exports.webHook = function webHook (req, res) { 
     return Promise.resolve() 
     .then(() => { 
      if (req.method !== 'POST') { 
      const error = new Error('Only POST requests are accepted'); 
      error.code = 405; 
      throw error; 
      } 
      . 
      .