我有一个简单的Cloud Function接收webhook,然后在BigQuery中进行流式插入 . 该代码基于此sample(除了我正在使用流式插入)
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);
});
};
这个功能在大多数情况下运行良好,但我确实偶尔会出现身份验证错误,然后就会消失 .
textPayload:“OTHER ERROR:{”code“:401,”errors“:[{”message“:”请求具有无效的身份验证凭据 . 预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据 . 请参阅https://developers.google.com/identity/sign-in/web/devconsole-project.","domain":"global","reason":"unauthorized"}],"message":"Request have验证凭据无效 . 预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据 . 请参阅https://developers.google.com/identity/sign-in/web/devconsole-project . “}”
我不确定auth是如何成为问题的,因为Cloud Function和BigQuery都在同一个项目中 .
1 回答
Cloud 功能团队的人员认为这可能是由于访问令牌生存时间(TTL)的问题,并提出了一个对我有用的解决方法 . 而不是在代码顶部初始化BigQuery(因为他们的所有示例都有),将初始化代码放在调用函数内部 .
做这个:
代替: