Firebase / Cloud Function 非常慢

ABC*_*ABC 5 javascript firebase google-cloud-functions google-cloud-firestore

我有一个执行以下操作的 Firebase 云函数:

const firestore = require('firebase-admin')
const functions = require('firebase-functions')
const regex = require('../../utils/regex')

exports = module.exports = functions.https.onCall((data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.')
  }

  if (!data['displayName']) {
    throw new functions.https.HttpsError('failed-precondition', 'An display name must be provided.')
  }

  if (!regex.noSpecialCharactersExceptSpace.test(data['displayName'])) {
    throw new functions.https.HttpsError('input-validation-failed', 'Your display name cannot have special characters in it.')
  }

  return firestore.firestore().collection('profiles').doc(context.auth.uid)
    .update({
      displayName: data['displayName']
    })
    .then(() => {
      console.info('Successful public profile update user='+ context.auth.uid)
      return { text: 'Your profile has successfully been updated' };
    })
    .catch((error) => {
      console.error('Error updating public profile user=' + context.auth.uid + ' error=' + error)
      throw new functions.https.HttpsError('failed-precondition', 'An error happened, our team will look into it.')
    })
})
Run Code Online (Sandbox Code Playgroud)

在我的前端,当我调用这个函数时,它可能需要 20-30 秒才能完成并返回一个状态代码。这种延迟确实会破坏用户体验。

改善响应时间的最佳方法是什么?

测试

  1. 从 UI 直接调用 Firestore 的解决速度非常快。因此,问题似乎不太可能是我们这边的 DNS。

  2. 其他从 UI 调用 Cloud Function 的 API,如“邀请朋友”,解决很快,不受此故障的影响。

  3. 呼叫其他的云功能,不返回一个承诺,但不喜欢的东西与邮戳发送电子邮件,都不会受到这种故障并快速解决令人难以置信。因此,问题似乎不在于 Firebase 项目 ( us-central1)的位置。虽然更改位置尚未经过测试。

  4. 故障只发生在这一项功能上。上面复制粘贴的那个。

  5. 受影响的函数与我们的其他函数之间的唯一区别是,有错误的函数为 Firestore 操作返回了一个 Promise。