Firestore 简单集合组使函数超时



我有一个计划每 2 分钟运行的云函数。 我目前正在使用 Http 测试该函数,并尝试运行一个简单的collectionGroup查询,如下所示

更新1 我更新了我的代码以处理offsetlimit但现在它对第一条记录工作正常,然后在获取第二条记录时挂起。

请检查代码段

/* eslint-disable promise/no-nesting */
/**
* @description
* This module will send out emails to different users who have alerts not sent out yet
* @algorithm
* 1 - Get all alerts where sent = false 
* 2 - Send out those alerts via the email module. 
*/
const functions = require("firebase-functions");
const { db } = require("../helpers/firestore");
// console.log('admin: ', admin);
let _allUserAlerts = [];
let counter = 0;
exports.sendEmailsToUsers = functions.pubsub
.schedule("every 2 minutes")
.onRun(context => {
return sendEmailsToUsers(context);
});
exports.testSendEmailsToUsers = functions.https.onRequest((req, res) => {
return sendEmailsToUsers("hello");
});
async function sendEmailsToUsers(context) {
try {
console.log("function execution")
let alerts = await db
.collectionGroup("alerts")
.where("sent", "==", false)
.limit(1)
.offset(counter)
.get();
alerts.forEach(_alert => {
if (_alert.exists) {
console.log("alert exists")
_allUserAlerts.push(_alert.data());
counter++;
return sendEmailsToUsers()
} else {
console.log("alert ends")
sendAlertsToEmail(_allUserAlerts)
}
})
} catch (err) {
console.log(err)
}
}
async function sendAlertsToEmail(alerts) {
console.log('alerts: ', alerts);
}

旧代码

/* eslint-disable promise/no-nesting */
/**
* @description
* This module will send out emails to different users who have alerts not sent out yet
* @algorithm
* 1 - Get all alerts where sent = false 
* 2 - Send out those alerts via the email module. 
*/
const functions = require("firebase-functions");
const { db } = require("../helpers/firestore");
const { Email } = require("../EmailModule");
const { groupBy } = require("../helpers/groupBy");
exports.sendEmailsToUsers = functions.pubsub
.schedule("every 2 minutes")
.onRun(context => {
return sendEmailsToUsers(context);
});
async function sendEmailsToUsers(context) {
try {
console.log("function execution")
let alerts = await db
.collectionGroup("alerts")
.where("sent", "==", false)
.get();
console.log('alerts: ', alerts);
} catch (err) {
console.log(err)
}
}

从字面上看,这是函数中的整个代码,但是函数超时了,我没有达到alertslog()。 我不明白这里可能有什么问题?我可能错过或没有到达这里的任何内容?任何帮助将不胜感激。

谢谢

也许这个过程只需要 60 多秒。您可以增加云函数的超时时间。您可以将其提高到 9 分钟,它应该可以工作。

否则,问题似乎不是来自函数本身。问题可能在这里的某个地方:const { db } = require("../helpers/firestore");。"db"不会到来,这就是您的代码在let alerts = await db停止的方式。

听起来您可能请求了太多数据来传输和存储在内存中而没有问题。 我建议改为使用limit()对数据进行分页,以便您可以批处理结果,而不会超出 Cloud Functions 服务器实例的限制(非常有限(。 从小处着手,逐步向上。

此问题的解决方案是升级当前节点版本。 默认情况下,云函数在已停止官方节点.js团队支持的Node 8上运行。因此,当我升级到Node 10时,它又开始完美地工作了!

最新更新