首页 > 解决方案 > 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);
  }
}

标签: node.jsamazon-web-servicesaws-lambdaamazon-cognito

解决方案


这可能是因为集成 Lambda 的 Cognito 强制执行超时为 5 秒 - 并且无法更改。另请注意,Cognito 将(重新)尝试调用该函数的最大次数为 3 次。

使用 Lambda 触发器自定义用户池工作流部分中,它指出:

重要 Amazon Cognito 同步调用 Lambda 函数。调用时,您的 Lambda 函数必须在 5 秒内响应。如果没有,Amazon Cognito 会重试调用。3 次尝试不成功后,函数超时。此 5 秒超时值无法更改。

因此,为了减少执行时间,值得考虑在可能的情况下引入缓存。包括数据库连接等。

但是请注意,您几乎无法控制 Lambda 的重复使用频率和重新启动频率,您需要在预热时间方面牢记这一点。


推荐阅读