简体   繁体   English

AWS Cognito Lambda触发两次

[英]AWS Cognito lambda triggers twice

I'm using an AWS Lambda function (using nodejs). 我正在使用AWS Lambda函数(使用nodejs)。

Once any request from APP to Cognito to signUp users. 从APP发送到Cognito的任何请求以注册用户。 Then I have set the Pre sign-up trigger to validate the user's customer and check users custom attribute available in our database or not. 然后,我设置了“ 预注册”触发器来验证用户的客户,并检查我们数据库中是否有可用的用户自定义属性。 If yes then return an error and else insert new records in DB and return the event to Cognito. 如果是,则返回错误,否则将新记录插入数据库并将事件返回给Cognito。

TimeoutInfo - 5 min. TimeoutInfo-5分钟。

It happens sometime in the request, not all the time. 它在请求中的某个时间发生,而不是一直发生。 RequestId as different. RequestId为不同的。 (it will trigger 3 times sometime and most of the time twice) (它将在某个时间触发3次,大部分时间两次)

Lambda trigger code as below. Lambda触发代码如下。

users/index.js 用户/ 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);
};

exports.handler = handler; Exports.handler =处理程序; users/users.js users / 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);
  }
}

This likely happens because of the Cognito-imposed execution timeout of 5 seconds for integration Lambdas - and it cannot be changed. 之所以可能发生这种情况,是因为集成Lambda的Cognito施加的执行超时为5秒-并且无法更改。 Also note that the maximum amount of times that Cognito will (re-)attempt to call the function is 3 times. 另请注意,Cognito尝试(重新)调用该函数的最大次数为3次。

In the Customizing User Pool Workflows with Lambda Triggers section it states that: 使用Lambda触发器自定义用户池工作流部分中,它指出:

Important Amazon Cognito invokes Lambda functions synchronously. 重要 Amazon Cognito同步调用Lambda函数。 When called, your Lambda function must respond within 5 seconds. 调用时,您的Lambda函数必须在5秒内响应。 If it does not, Amazon Cognito retries the call. 如果不是,则Amazon Cognito重试该呼叫。 After 3 unsuccessful attempts, the function times out. 尝试3次失败后,该功能超时。 This 5-second timeout value cannot be changed. 此5秒超时值无法更改。

Therefore to reduce the execution time it would be worth to consider introducing caching where possible. 因此,为减少执行时间,有必要考虑在可能的地方引入缓存。 Including database connections etc. 包括数据库连接等

Do however note that you have little to no control over how often Lambdas are re-used versus re-launched and you will need to keep this in mind in terms of warm-up times. 但是请注意,您几乎无法控制Lambda的重用和重新启动的频率,您需要在预热时间方面牢记这一点。

Any chance you are running your lambda in a VPC? 您是否有可能在VPC中运行Lambda? I've seen similar behavior with a Cognito trigger that ran in a VPC when it was cold started. 我已经看到Cognito触发器在冷启动时在VPC中运行的类似行为。 Once the lambda was warm the problem went away 一旦lambda变热,问题就消失了

My hunch was that internally Cognito has a very short timeout period for executing the trigger, and if the trigger didn't reply in time, it would automatically retry. 我的直觉是内部Cognito执行触发器的超时时间非常短,如果触发器未及时答复,它将自动重试。

We ended up having to add logic to our trigger to test for this scenario so that we weren't duplicating writes to our database. 我们最终不得不在触发器中添加逻辑以测试这种情况,以便避免重复写入数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM