|
| 1 | +import * as cdk from "aws-cdk-lib"; |
| 2 | +import * as lambda from "aws-cdk-lib/aws-lambda"; |
| 3 | +import * as sfn from "aws-cdk-lib/aws-stepfunctions"; |
| 4 | +import * as tasks from "aws-cdk-lib/aws-stepfunctions-tasks"; |
| 5 | + |
| 6 | +export class CdkStack extends cdk.Stack { |
| 7 | + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { |
| 8 | + super(scope, id, props); |
| 9 | + |
| 10 | + // Set hit interval in seconds |
| 11 | + const hitIntervalInSeconds = 3; |
| 12 | + const hitDurationInSeconds = 1 * 60; // 1 minute * 60 seconds |
| 13 | + |
| 14 | + // The lambda function |
| 15 | + const playLambda = new lambda.Function(this, "playLambda", { |
| 16 | + description: "Lambda function that pulls will be triggered", |
| 17 | + handler: "playLambda.handler", |
| 18 | + runtime: lambda.Runtime.NODEJS_14_X, |
| 19 | + code: lambda.Code.fromInline(` |
| 20 | +exports.handler = async (event, context, callback) => { |
| 21 | + console.log('event: ', event); |
| 22 | +
|
| 23 | + let index = event.iterator.index; |
| 24 | + let step = event.iterator.step; |
| 25 | + let count = event.iterator.count; |
| 26 | +
|
| 27 | + // do your business |
| 28 | +
|
| 29 | + callback(null, { |
| 30 | + index, |
| 31 | + step, |
| 32 | + count, |
| 33 | + continue: index < count ? "CONTINUE" : "END", |
| 34 | + }); |
| 35 | +}; |
| 36 | + `), |
| 37 | + }); |
| 38 | + |
| 39 | + const ConfigureCount = new sfn.Pass(this, "ConfigureCount", { |
| 40 | + result: { |
| 41 | + value: { |
| 42 | + count: Math.round(hitDurationInSeconds / hitIntervalInSeconds), |
| 43 | + index: 0, |
| 44 | + step: 1, |
| 45 | + }, |
| 46 | + }, |
| 47 | + resultPath: "$.iterator", |
| 48 | + }); |
| 49 | + |
| 50 | + const Iterator = new tasks.LambdaInvoke(this, "PlayTask", { |
| 51 | + lambdaFunction: playLambda, |
| 52 | + payloadResponseOnly: true, |
| 53 | + retryOnServiceExceptions: false, |
| 54 | + resultPath: "$.iterator", |
| 55 | + }); |
| 56 | + |
| 57 | + const Wait = new sfn.Wait(this, "Wait", { |
| 58 | + time: sfn.WaitTime.duration(cdk.Duration.seconds(hitIntervalInSeconds)), |
| 59 | + }).next(Iterator); |
| 60 | + |
| 61 | + const Done = new sfn.Succeed(this, "Done"); |
| 62 | + |
| 63 | + const IsCountReached = new sfn.Choice(this, "IsCountReached", { |
| 64 | + comment: "If the count is reached then end the process", |
| 65 | + }) |
| 66 | + .when(sfn.Condition.stringEquals("$.iterator.continue", "CONTINUE"), Wait) |
| 67 | + .otherwise(Done); |
| 68 | + |
| 69 | + new sfn.StateMachine(this, "PlayStateMachine", { |
| 70 | + stateMachineName: "PlayStateMachine", |
| 71 | + definition: ConfigureCount.next(Iterator).next(IsCountReached), |
| 72 | + }); |
| 73 | + } |
| 74 | +} |
0 commit comments