以编程方式激活 firebase 云函数中的重试

Car*_*etz 5 firebase google-cloud-functions google-cloud-firestore

我正在部署 firebase 云功能,以通过持续部署来监听我们的 firestore 中的变化。

我只能找到手动激活重试的方法。这与我们裁谈会的做法背道而驰。

查看正常的gcp 云功能,可以在部署时给出重试标志。但我在 firebase-cli 或 firebase-functions 界面(2.1.0)中找不到类似的选项

关于如何解决这个问题有任何提示吗?卡斯滕

jim*_*ron 6

You can enable retries in Firebase Functions using GCloud Console, manually by hand. Programmatically retrying trigger-based functions was added in firebase-functions 3.10.0 (see changelog and associated pull request).

Since it's not entirely obvious from the PR or the docs, here's a quick example of the syntax:

export const myFirebaseFunc = functions
  .runWith({
    failurePolicy: {
      retry: {},
    },
    memory: '512MB',
    timeoutSeconds: 60,
  })
  .firestore.document('/path/to/some/doc')
  .onCreate(async (snap, context) => {
   /* do stuff */
 })
Run Code Online (Sandbox Code Playgroud)

At the time of writing this, it looks like the failure policy is simply on or off. Thus, this is equivalent

export const myFirebaseFunc = functions
  .runWith({
    failurePolicy: true,
    memory: '512MB',
    timeoutSeconds: 60,
  })
  .firestore.document('/path/to/some/doc')
  .onCreate(async (snap, context) => {
   /* do stuff */
 })
Run Code Online (Sandbox Code Playgroud)

Some caveats:

  • You'll also have to deploy with --force

  • You can enable retries only on triggered functions, not http-called functions.

  • It would be idiotic not to build in some safeguards. Retry policy maxes out at 7 days, and bills just like any other function invocation, so if you have some unhandled error, it could repeatedly run for a full week. You can use context.eventTimestamp to know when the first attempt roughly started.

Read this: https://firebase.google.com/docs/functions/retries and make sure your function in idempotent.

It was also difficult to discover what to return to force a retry or avoid a retry. Triggered Firebase functions must return a Promise. (See this vid)

A retry-enabled Firebase function will retry if:

  • it returns a rejected promise
  • throws an exception
  • or the function times out

That means that if you run into an error that you know won't eventually resolve itself with a retry (i.e. you want to stop the function execution and not retry), you can return Promise.resolve({message: 'some message'});


Dou*_*son 3

目前没有使用 Firebase CLI 进行部署的类似选项。

这是 Firebase 团队正在研究的内容,因此请继续关注更新。