Home > Enterprise >  Cloud Function finished with status: 'timeout' while adding data to Firestore
Cloud Function finished with status: 'timeout' while adding data to Firestore

Time:04-02

Here's the code,

exports.onEmailRecieved = functions.database
  .ref("/emails/recieved/{id}/")
  .onCreate(async (snapshot, context) => {
    const email = snapshot.val();
    const id = context.params.id;

    const trimmedEmailBody = String(email.body).replace("\n", "").trim();

    if (trimmedEmailBody === cmd) {
      const queueRef = fs.collection("requests").doc("all").collection("queue");

      await fs
        .runTransaction(async (t) => {
          const doc = await t.get(queueRef);
          const size = doc.size;

          console.log(`Size: ${size}`);

          console.log("Adding to queue.");

          await queueRef
            .add({
              email: email.email,
              subject: email.subject,
              body: email.body,
            })
            .then(() => {
              console.log("Successfully added to queue.");
            })
            .catch((err) => {
              console.log(err);
            })
            .finally(() => {
              console.log("It's finally over.");
            });

          return console.log("Worked?");
        })
        .then(() => {
          return console.log("Complete");
        })
        .catch((err) => {
          return console.log(err);
        });

      return console.log("Worked I guess.");
    } else {
      return console.log("Not equal.");
    }
  });

Don't mind the bunch of useless console.logs. Added em to debug the error.

That first console.log gets called and then nothing, no then, catch or finally functions get triggered and I get a function finished with status: 'timeout' message in the logs.

What I'm doing wrong?

CodePudding user response:

The add() method returns a promise which then when you await a promise, the function is paused in a non-blocking way until the promise settles. It will wait for the transaction to be finished before resolving the creation of the document which results in timeout of the cloud function which by default is 1min. By removing the await on the add method you're instead executing the function. See code below:

messageRef
.add({
  email: "email",
  subject: "subj",
  body: "body",
})
.then(() => {
  console.log("Successfully added to queue.");
})
.catch((err) => {
  console.log(err);
})
.finally(() => {
  console.log("It's finally over.");
});

This will now return something like this:

Size: 1
Adding to queue.
test
Successfully added to queue.
It's finally over.

For more relevant information, you may check this documentations:

  • Related