【发布时间】:2022-12-20 03:13:01
【问题描述】:
我有一个谷歌云功能,可以将通知发送到 firebase 主题。 该功能工作正常,直到突然,它开始同时发送多个通知 2 或 3。联系 Firebase 支持团队后,他们告诉我应该使函数幂等,但我不知道怎么做,因为它是一个可调用函数。 更多详情,this is a reference question containing more detail about the case。 下面是函数的代码。
- 更新 2
这是 admin sdk 中的一个错误,他们在上一个版本中解决了它。
更新
该函数已经是幂等的因为它是一个事件驱动函数
上面的链接包含函数日志,因为它只运行一次。
经过 2 个月的往返,它出现了firebase admin sdk 的问题函数代码getMessaging().sendToTopic() 已重试 4 次,并且原始请求因此在抛出错误并终止函数之前默认重试 5 次。所以重复通知的原因是 admin sdk 由于某种原因有时无法到达 FCM 服务器。它尝试向所有 subs 发送通知,但在中途或在发送所有通知之前它收到错误,因此它从开始,所以有些用户会收到一个通知,有些用户会收到 2、3、4。
现在的问题是如何防止这些默认重试或如何使重试从出现错误的地方继续。可能我会问一个单独的问题。
现在我通过防止来自接收者(移动客户端)的重复通知做了一个天真的解决方案。如果它在一分钟内收到多个通知具有相同的内容,则只显示一个。
const functions = require("firebase-functions");
// The Firebase Admin SDK to access Firestore.
const admin = require("firebase-admin");
const {getMessaging} = require("firebase-admin/messaging");
const serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mylinktodatabase.firebaseio.com",
});
exports.callNotification = functions.https.onCall( (data) => {
// Grab the text parameter.
const indicator = data.indicator;
const mTitle = data.title;
const mBody = data.body;
// topic to send to
const topic = "mytopic";
const options = {
"priority": "high",
"timeToLive": 3600,
};
let message;
if (indicator != null ) {
message = {
data: {
ind: indicator,
},
};
} else {
message = {
data: {
title: mTitle,
body: mBody,
},
};
}
// Send a message to devices subscribed to the provided topic.
return getMessaging().sendToTopic(topic, message, options)
.then(() => {
if (indicator != null ) {
console.log("Successfully sent message");
return {
result: "Successfully sent message", status: 200};
} else {
console.log("Successfully sent custom");
return {
result: "Successfully sent custom", status: 200};
}
})
.catch((error) => {
if (indicator != null ) {
console.log("Error sending message:", error);
return {result: `Error sending message: ${error}`, status: 500};
} else {
console.log("Error sending custom:", error);
return {result: `Error sending custom: ${error}`, status: 500};
}
});
});
【问题讨论】:
-
你有没有检查我的answer?
-
抱歉来晚了,我正在调查其他应用程序/错误。
标签: javascript google-cloud-functions firebase-admin idempotent