Search code examples
javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

Firebase functions TLS & Socket hang up error when i run my function


I am getting this TLS & Socket hang up error each time my firebase function tries to access a collection group in my firestore database, any ideas what could be causing this error?

Exception from a finished function: FetchError: request to ... failed, reason: socket hang up

Firestore query error: FetchError: request to ... failed, reason: Client network socket disconnected before secure TLS connection was established"

const {onSchedule} = require("firebase-functions/v2/scheduler");
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");
initializeApp();
const db = getFirestore();
exports.checkOrders = onSchedule(
    {
      timeoutSeconds: 300,
      region: "europe-central2",
      schedule: "05 03 * * *",
    }, async (event) => {
      const now = new Date();
      const today = now.setHours(3, 0, 0, 0);
      const yearToday = now.getFullYear();
      const monthToday = now.getMonth() + 1;
      const dayToday = now.getDate();
      const formattedToday = `${yearToday}, ${monthToday < 10 ? "0" + monthToday : monthToday}, ${dayToday < 10 ? "0" + dayToday : dayToday}`;

      console.log(today);
      console.log(formattedToday);

      const mainSnapshot = await db.collection("xxx")
          .where("activity_status", "in", ["Active", "ActiveLast", "Pending", "Inactive", "", "Error"])
          .get();

      mainSnapshot.forEach((doc) => {
        const Data = doc.data();
        indexFunctions(Data, today, formattedToday);
      });

      async function indexFunctions(Data, today, formattedToday) {
        let retryCount = 0;
        const maxRetries = 3;

        const updateObject = {};
        let iterationCount = 1;
        const parentID = String(Data.id);
        const updateBatch = db.batch();
        while (retryCount < maxRetries) {
          try {
            const querySnapshot = await db.collectionGroup("qqq")
                .where("parent_id", "==", parentID).get();

// This is where the code starts throewing those errors, so i dont need to show the rest of the code.

My functions have the right permissions & the problem doesn't seem to be coming from my code, at least i don't think, because i tried stripping it down to the bone but still got these errors. I have tried checking for proxies, updating all dependancies and everything i could think of. Any help would be appreciated.


Solution

  • Your indexFunctions function is async and returns a promise. However, you're doing nothing in the calling code to ensure that the promise returned by it is fully settled before the top-level function returns. That means the top-level function is going to terminate before the async work is complete, and you can see errors like the one you're seeing now. It's absolutely a requirement to settle all promises invoked by Cloud Functions code - see the documentation on the matter. Cloud Functions will forcibly shut down async code that isn't awaited before termination.

    In particular, this code is wrong:

          mainSnapshot.forEach((doc) => {
            const Data = doc.data();
            indexFunctions(Data, today, formattedToday);
          });
    

    The call to indexFunctions is not blocking the forEach loop. The loop is completing before any of the async work is complete.

    If you want to correctly await promises in a loop, see this question: Using async/await with a forEach loop

    It's probably easiest if you use a for/of loop instead of forEach so you can use await inside it.

    Since you didn't show the rest of the code, you could be making the same mistake elsewhere, so you will have to check that on your own.