How can I setup a Firebase Function Gen 2 HTTP onRequest so that it will retry a set number of times if it encounters an error?
And how do I set the number of times it will retry, because even for Gen 1 functions I have no idea how.
For example, I have a Firebase Function that is acting like a pingback. When I receive the pingback I want to run some code, and retry that code again if it fails the first time.
This is how I think it would be written for Firebase Function Gen 1:
import * as functions from "firebase-functions";
export const myFunction = functions
.runWith({ failurePolicy: true }) // This will apparently trigger retries, how many times I have no idea
.https.onRequest(async (req, res) => {
try {
// Try something async
await thisMightThrowError();
} catch (error) {
// Error found so trigger a retry
logger.error(error);
res.status(500).send(error);
return;
}
// Everything worked
res.status(200).send("Success");
return;
});
This is my attempt for Firebase Function Gen 2, but the HTTP Options object does not have failurePolicy
property. Is there another way to get retries working for this?
import { onRequest } from "firebase-functions/v2/https";
export const myFunction = onRequest(
{
failurePolicy: true, // This is invalid. The HTTPS Options object does not have "failurePolicy" property
},
async (req, res) => {
try {
// Try something async
await thisMightThrowError();
} catch (error) {
// Error found so trigger a retry
logger.error(error);
res.status(500).send(error);
return;
}
// Everything worked
res.status(200).send("Success");
return;
},
);
It's not possible to make an HTTP type function retry on its own. The retry must come from the client making the request - it can check the response from the function and decide if it should try again.
If the client can't retry, then your HTTP function must delegate to another function that can retry. One option here is to use a pubsub function. Have the HTTP function send a message to the pubsub function via its named topic. The pubsub function can then be configured to retry itself as necessary.