firebase - Firebase Cloud Function + Firestore 性能问题
问题描述
我有一个 Firebase 云函数来处理一些用户注册信息,我发现它非常慢,因为该函数实际上在做什么。通常,此功能大约需要 6-7 秒才能完成。我已将其缩小到花费最多时间(大约 5 秒)的这条线:
let snapshot = await admin.firestore().collection('users').doc(context.auth.uid).get();
if (!snapshot.exists) {
throw new functions.https.HttpsError('not-found', 'User profile could not be found');
}
90% 的时间,被提取的文档应该存在。我原以为这会以惊人的速度返回;相反,它通常需要大约 5 秒才能返回。任何关于我可能做错的想法都将不胜感激。
注意:一切都部署到us-central-1
.
这是我进行的一次分析运行的日志片段:
5:36:51.248 AM addMember Function execution started
5:36:52.256 AM addMember Checkpoint #1
5:36:52.256 AM addMember Checkpoint #2
5:36:57.253 AM addMember Checkpoint #3
5:36:57.254 AM addMember Checkpoint #4
5:36:57.597 AM addMember Checkpoint #5
5:36:57.982 AM addMember Checkpoint #6
5:36:58.051 AM addMember Function execution took 6804 ms, finished with status code: 200
上面的代码片段是在 and 之间执行Checkpoint #2
的Checkpoint #3
;它是这两个语句之间的唯一代码行。我已经重复执行了这个函数(10 次),完成该块的平均时间约为 5 秒。
编辑:我已经能够缩小代码范围以尝试识别任何瓶颈。这是我所拥有的(仍然表现出缓慢的行为)
函数/index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const addMember = require('./add-member');
admin.initializeApp();
exports.addMember = functions.https.onCall(addMember(admin));
函数/add-member.js:
const functions = require('firebase-functions');
const { generateCode} = require('../common');
module.exports = (admin) => async ({ email }, context) => {
console.log('Checkpoint #1')
const payload = {
code: generateCode(),
invited: new Date(),
joined: null
};
console.log('Checkpoint #2');
let snapshot = await admin.firestore().collection('users').doc(context.auth.uid).get();
if (!snapshot.exists) {
throw new functions.https.HttpsError('not-found', 'User profile could not be found');
}
console.log('Checkpoint #3');
return Promise.resolve(payload);
};
解决方案
对于它的价值,我遇到了这些很有帮助的东西。函数的速度并不完全符合我的期望/希望,我开始倾向于它是实例的 CPU 速度(128MB)。无论如何,希望其他人会发现这些帖子有用:
https://stackoverflow.com/a/47985480/541277 https://github.com/firebase/functions-samples/issues/170#issuecomment-323375462
推荐阅读
- python - 基于两个不同 DataFrame 比较的总和值
- ios - 获取远程视频的预览图像
- r - 如何在每列过滤的数据上从另一个数据框中创建具有自定义列的新数据框
- angular-material - 使用 Mat select angular 5 的模板解析错误
- c++ - 关于 c++ 中缀包含两个幂符号时转换为后缀(^^)
- azure - 问:带有故障转移的 Azure S2S VNet VPN
- react-native - React Navigation - 堆栈导航器屏幕自动调用 goBack()
- php - Laravel Eloquent - 为什么 take(n) 有效但 limit(n) 无效?
- powershell - 在不使用外部程序或库的情况下使用 Windows PowerShell/.Net 创建证书和 CSR
- angular - Angular 7 - 虚拟滚动与异步订阅相结合