node.js - AWS Cognito lambda 触发两次
问题描述
我正在使用 AWS Lambda 函数(使用 nodejs)。
一旦 APP 向 Cognito 发出任何请求以注册用户。然后我设置了注册前触发器来验证用户的客户并检查我们数据库中是否可用的用户自定义属性。如果是,则返回错误,否则在 DB 中插入新记录并将事件返回给 Cognito。
TimeoutInfo - 5 分钟。
它在请求中的某个时间发生,而不是一直发生。RequestId 不同。(有时会触发 3 次,大部分时间会触发 2 次)
Lambda 触发代码如下。
用户/index.js
const handler = async (event, context) => {
log.info('createUserLambda:start');
// immediately return once the call back is called to avoid
// lambda time out because of any open db connections
context.callbackWaitsForEmptyEventLoop = false;
return await preUserCreate(event);
};
export.handler = 处理程序;用户/users.js
export const preUserCreate = async (event) => {
log.info('preUserCreate:Start');
let userAttributes = event.request.userAttributes;
const currentDate = moment().utc().format('YYYY-MM-DD HH:mm:ss');
try {
let userParams = {
'docStatus': 'VRF'
};
let docParams = [{
'docNumber': userAttributes['custom:document_number'] ? userAttributes['custom:document_number'] : '',
'createdDate': currentDate
}];
if (docParams.length && docParams[0].docNumber) {
let documentExit = await getDocs(docParams[0].docNumber);
if (documentExit.length) {
log.info('preUserCreate:Error');
throw new Error('Document number already exist.');;
}
}
let documentRs = await insertDocument(docParams);
userParams = {
'did': documentRs[0].id,
'id': event.userName,
'createdDate': currentDate,
'updatedDate': currentDate,
...userParams
};
let userRs = await insertUser([userParams]);
if (docParams.length && docParams[0].docNumber) {
let resultData = await getUserAccountFromAPI(docParams[0].docNumber);
if (resultData) {
let foramattedData = await formattedAccountsData(resultData, userRs[0].id, documentRs[0].id);
await insertUserAccounts(foramattedData);
}
}
log.info('preUserCreate:Success');
event.response = {
'autoConfirmUser': false,
'autoVerifyPhone': false,
'autoVerifyEmail': false
};
return event;
} catch (error) {
log.info('preUserCreate:Error', error);
throw (error);
}
}
解决方案
这可能是因为集成 Lambda 的 Cognito 强制执行超时为 5 秒 - 并且无法更改。另请注意,Cognito 将(重新)尝试调用该函数的最大次数为 3 次。
在使用 Lambda 触发器自定义用户池工作流部分中,它指出:
重要 Amazon Cognito 同步调用 Lambda 函数。调用时,您的 Lambda 函数必须在 5 秒内响应。如果没有,Amazon Cognito 会重试调用。3 次尝试不成功后,函数超时。此 5 秒超时值无法更改。
因此,为了减少执行时间,值得考虑在可能的情况下引入缓存。包括数据库连接等。
但是请注意,您几乎无法控制 Lambda 的重复使用频率和重新启动频率,您需要在预热时间方面牢记这一点。
推荐阅读
- monitoring - 尝试使用 Prometheus 抓取目标时权限被拒绝
- flutter - gradle build失败任务':webview_flutter:compileDebugJavaWithJavac'的执行失败
- flutter - 使用默认大小自动调整第三方颤振小部件的大小
- javascript - 如何识别图钉在 bingMaps 的当前视图/缩放中是否可见?如果不可见 setView 到图钉的位置?
- go - 在整个应用程序中使用相同的 zerolog 设置
- twitter-bootstrap - 表单中输入字段的右对齐不起作用
- android-studio - AVD 无法在 ubuntu 18.04 LTS 上的 android studio 4.1.2 上启动
- dm-script - 如何从 dm-script 中的长字符串数据中获取图像
- swift - MacOS 故事板 - 带有图像和下方数十个按钮的结构
- python - 非阻塞 PyQT 作为一个额外的 GUI 可视化主进程的结果?