我有一个非常简单的简单云函数,该函数将单个值写入实时数据库。代码在这篇文章的底部。
看着日志,我发现执行时间非常不一致。这是屏幕截图:
您可以看到它低至3毫秒(太好了!),而高至579毫秒(非常糟糕-我已经看到它达到了1000毫秒)。结果是我的聊天室实施出现了非常明显的延迟,有时消息的发送顺序有时会乱序地添加。 (即“ 1”,“ 2”,“ 3”被接收为“ 2”,“ 3”,“ 1”))
为什么执行时间会发生巨大变化?冷启动与热启动似乎并不适用,因为您可以看到这些调用是一个接一个地直接发生的。我也找不到实时dbs每秒写入量的任何记录限制,与Firestore文档中的每秒1个写入量限制不同。
这是代码:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const messagesRef = admin.database().ref('/messages/general');
export const sendMessageToChannel = functions.https.onCall(async (data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
'failed-precondition',
'User must be logged-in.'
);
}
try {
await messagesRef.push({
uid: context.auth.uid,
displayName: data.displayName,
body: data.body
});
} catch (error) {
throw new functions.https.HttpsError('aborted', error);
}
});
编辑:两年前,我见过this similar question,响应者指出任务本身的执行时间可变。
是这种情况吗?实时数据库的写入时间是否大不相同(从3毫秒到1000毫秒,变化约330倍!)?
答案 0 :(得分:0)
根据代码,这是很难控制的。
你在那里有很多步骤:\
因此,您不能仅仅依靠响应时间来组织消息传递顺序。
您应该从客户端内部设置服务器端时间戳以进行跟踪。
您可以使用以下解释过的代码实现此目的:
try {
message.createdAt = firebase.firestore.FieldValue.serverTimestamp() // server-side timestamp
... // calls to functions
} catch(err) {
console.log("Couldn't set timestamp or send to functions")
}
通过这种方式,您可以在发送消息之前为要保存的消息设置服务器端时间戳,这样您的用户就会在消息被注册(时间戳)、保存(函数调用)和确认(发送时为 200)时看到。