首页 > 解决方案 > AWS StepFunction Lambda 等待令牌 - 何时发生等待?

问题描述

AWS StepFunctions 支持回调模型。文档内容如下:

回调任务提供了一种在返回任务令牌之前暂停工作流的方法。一项任务可能需要等待人工批准、与第三方集成或调用遗留系统。对于此类任务,您可以无限期暂停 Step Functions,并等待外部流程或工作流程完成。对于这些情况,Step Functions 允许您将任务令牌传递给某些集成服务。该任务将暂停,直到它通过 SendTaskSuccess 或 SendTaskFailure 调用接收到该任务令牌。

如果使用 CDK 定义状态机以调用 lambda 作为 Step Function 映射的一部分(即它在循环中):

LambdaInvoke myLambdaStepFunction = LambdaInvoke.Builder.create(this, "MyLambdaStepFunction ")
                                                      .lambdaFunction(myLambdaFunction)
                                                      .integrationPattern(IntegrationPattern.WAIT_FOR_TASK_TOKEN)
                                                      .build();

stepfunctions.Map loopSteps = stepfunctions.Map.Builder.create(this, "LambdaLoop")
                                                    .maxConcurrency(1)
                                                    .build();
loopSteps.iterator(myLambdaStepFunction);

StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
                                             .stateMachineType(StateMachineType.STANDARD)
                                             .timeout(Duration.minutes(5))
                                             .definition(deployAllIncrementallySteps)
                                             .build();

什么时候出现等待令牌?

  1. 是在第一次调用 lambda 之后吗?
  2. 是在第一次调用 lambda 之前吗?

标签: amazon-web-servicesaws-lambdaaws-cdkaws-step-functions

解决方案


IntegrationPattern.WAIT_FOR_TASK_TOKEN在执行了集成的 Lambda 之后,将等待令牌。这是模式:

  1. Your lambda when called will have a token passed to it by AWS in the Step Function event if you specify it in the payload, e.g. here I specify the token to be in the JSON payload supplied to the Lambda at the path of $.token and the remainder of the input at $.input:
LambdaInvoke myLambdaStep= LambdaInvoke.Builder.create(this, "MyLambdaStep")
                                .lambdaFunction(myLambdaFunction)
                                .integrationPattern(IntegrationPattern.WAIT_FOR_TASK_TOKEN)
                                .payload(TaskInput.fromObject(Map.of("token", JsonPath.getTaskToken(), "input", JsonPath.stringAt("$.input"))))
                                .build();
  1. Within your Lambda function, you are responsible for parsing the token from the event and passing this token to some outside agent: at some point, that agent needs to call sendTaskSuccess or sendTaskFailure with that token to indicate that the work being carried out by that agent is complete. The external agent can be anything at all (another Lambda, an EC2 server doing some work for you, an external webhook, anything - it just needs to make the call back to AWS when its work is complete).

  2. 当 AWS 收到您的代理的调用时,它将根据代理发出的成功或失败调用在您的步进机器中调用适当的下一步。


推荐阅读