使用批处理对象时,云功能停止执行

时间:2019-01-19 20:45:02

标签: google-bigquery google-cloud-firestore google-cloud-functions

我正在使用Google Cloud Function在bigQuery上执行查询并将结果存储在firestore中。

我的问题是,一旦我尝试使用firestore批处理对象,云功能就会停止执行。

使用二分法,我认为是在添加批处理目标代码时函数突然停止工作。

我试图将函数的内存增加到1GB,但是没有运气。 (当前使用的是128mb)

const {BigQuery}  = require('@google-cloud/bigquery');
const {Firestore} = require('@google-cloud/firestore');

const bigquery   = new BigQuery  ();
const firestore  = new Firestore ();

const fsCollectionName = 'ul_queteur_stats_per_year';


const queryStr = "the bigquery query";


function handleError(err){
  //skipped
}

/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {!Object} event Event payload.
 * @param {!Object} context Metadata for the event.
 */
exports.ULQueteurStatsPerYear = (event, context) => {
  const pubsubMessage = event.data;
  const parsedObject  = JSON.parse(Buffer.from(pubsubMessage, 'base64').toString());

  console.log("Recieved Message : "+JSON.stringify(parsedObject));
  //{ ul_id:parsedObject.ul_id }

  const queryObj = {
    query: queryStr,
    params: {
      ul_id: parsedObject.ul_id
    }
  };

  bigquery
    .query(queryObj)
    .then((data) => {
      console.log("Query Successful, # rows : "+data.length+" data[0].length:"+data[0].length);
      //rows : [{"amount":367.63,"weight":2399.3,"time_spent_in_minutes":420}]
      const rows = data[0];
      console.log("Query Successful");

      const batch       = firestore.batch();

      console.log("Batch Created ");

      console.log("Getting Collection");
      const collection  = firestore.collection(fsCollectionName);
      console.log("Getting Collection '"+fsCollectionName+"' retrieved");
      //#####################################
      for(let i=0;i<rows.length;i++)
      {
        console.log("getting a new DocId");

        const docRef = collection.doc();

        console.log("Adding to docRef='"+docRef.id+"' : "+JSON.stringify(rows[i]));
        batch.set(docRef, rows[i]);
        console.log("Added to batch");
      }


      console.log("Commiting batch insert");
      batch.commit().then(() => {
        console.log('Successfully executed batch');
      });
      //#####################################

    })
    .catch(err => {
      handleError(err);
    });

};

预期:

数据已插入Firestore

实际结果:

如果我删除了之间的代码       // ###################################

然后我在stackdriver中获得每个日志。 (第一个说有420行)

如果我让代码之间       // ##################################### (或者只是batch.commit()部分,或者只是for循环部分)

我只得到第一个日志,然后什么也没有。

  

查询成功,#行:1个数据[0]。长度:420

即使我将整个代码放在带有console.log异常的try / catch块中,在堆栈驱动程序中也看不到错误。

解决方案

解决方案是返回bigquery承诺。

因此上述代码应更改为:

return bigquery
.query(queryObj)
.then(...);

感谢Doug的帮助!

1 个答案:

答案 0 :(得分:3)

您需要返回一个承诺,该承诺将在所有异步工作完成后解决。现在,您什么也不返回,这意味着该函数将在查询完成之前立即终止并关闭。

您需要注意代码正在使用的所有承诺,包括查询和所有批处理提交。您不能忽略任何API返回的任何承诺,否则工作将在完成之前终止。

相关问题