internal QueueRecorder(Construct scope, string id, QueueRecorderProp props = null) : base(scope, id) { var table = new Table(this, "QueueRecorderTable", new TableProps { PartitionKey = new Attribute { Name = "id", Type = AttributeType.STRING } }); // Defines a new lambda resource var hello = new Function(this, "HelloHandler", new FunctionProps { Runtime = Runtime.NODEJS_10_X, // execution environment Code = Code.FromAsset("lambda"), // Code loaded from the "lambda" directory Handler = "hello.handler", // file is "hello", function is "handler" Environment = new Dictionary <string, string> { { "TABLE_NAME", table.TableName } } }); table.GrantReadWriteData(hello); hello.AddEventSource(new SqsEventSource(props.inputQueue)); }
internal SolarStack(Construct scope, IStackProps props = null) : base(scope, AWSConstructs.Names.Stack, props) { const string lambdaSource = "src/LambdaHandlers/bin/release/netcoreapp3.1/LambdaHandlers.zip"; var ingressQueue = new Queue(this, nameof(AWSConstructs.Names.FroniusIngressQueue), new QueueProps { Encryption = QueueEncryption.KMS_MANAGED, QueueName = AWSConstructs.Names.FroniusIngressQueue, VisibilityTimeout = Duration.Seconds(43200) }); var realtimeDataTable = new Table(this, AWSConstructs.Names.RealtimeDataTable, new TableProps { PartitionKey = new Attribute { Name = AWSConstructs.Names.RealtimeDataTablePartitionKey, Type = AttributeType.STRING }, SortKey = new Attribute { Name = AWSConstructs.Names.RealtimeDataTableSortKey, Type = AttributeType.NUMBER }, BillingMode = BillingMode.PAY_PER_REQUEST, TableName = AWSConstructs.Names.RealtimeDataTable, Stream = StreamViewType.NEW_IMAGE }); var ingressFunction = new Function(this, nameof(AWSConstructs.Names.FroniusIngressHandler), new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Code = Code.FromAsset(lambdaSource), Handler = LambdaHandlers.FroniusRealtimeHandler.HandlerName, FunctionName = AWSConstructs.Names.FroniusIngressHandler, Timeout = Duration.Minutes(5) }); ingressFunction.AddEventSource(new SqsEventSource(ingressQueue)); _ = realtimeDataTable.GrantReadWriteData(ingressFunction); _ = realtimeDataTable.Grant(ingressFunction, "dynamodb:DescribeTable"); var aggregateFunction = new Function(this, nameof(AWSConstructs.Names.RealtimeDataAggregatorHandler), new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Code = Code.FromAsset(lambdaSource), Handler = LambdaHandlers.RealtimeDataAggregatorHandler.HandlerName, FunctionName = AWSConstructs.Names.RealtimeDataAggregatorHandler, Timeout = Duration.Minutes(5) }); aggregateFunction.AddEventSource(new DynamoEventSource(realtimeDataTable, new DynamoEventSourceProps { StartingPosition = StartingPosition.LATEST, ParallelizationFactor = 10, BatchSize = 1 })); _ = realtimeDataTable.GrantReadWriteData(aggregateFunction); _ = realtimeDataTable.Grant(aggregateFunction, "dynamodb:DescribeTable"); }
public ConsumerStack(Construct scope, string name, double memory, Vpc vpc, StackProps props = null) : base(scope, $"consumer-{name}", props) { // pricing - lambda // 1 milhão de solicitações gratuitas por mês e // 400.000 GB/segundos de tempo de computação por mês. // // pricing - sqs // Primeiro milhão de solicitações/mês - padrao: Gratuito - fifo: Gratuito // De 1 milhão a 100 bilhões de solicitações mês - padrão: 0,40 USD - fifo: 0,50 USD // De 100 milhões a 200 bilhões de solicitações/mês - padrão: 0,30 USD - fifo: 0,40 USD // Mais de 200 bilhões de solicitações/mês - padrão: 0,24 USD - fifo: 0,35 USD _function = new Function(this, $"consumer-{name}-lambda", new FunctionProps() { FunctionName = name, MemorySize = memory, Runtime = Runtime.DOTNET_CORE_3_1, Handler = "Lambda::Lambda.Function::Handler", Code = Code.FromAsset("../tools/consumer"), Timeout = Duration.Seconds(20), LogRetention = RetentionDays.ONE_DAY, Vpc = vpc, VpcSubnets = new SubnetSelection() { SubnetType = SubnetType.PRIVATE } }); _deadletter = new Queue(this, $"consumer-{name}-deadletter", new QueueProps() { QueueName = name + "-deadletter", VisibilityTimeout = Duration.Seconds(30), RetentionPeriod = Duration.Days(10) }); ; _queue = new Queue(this, $"consumer-{name}-queue", new QueueProps() { QueueName = name, VisibilityTimeout = Duration.Seconds(30), RetentionPeriod = Duration.Days(10), DeadLetterQueue = new DeadLetterQueue() { MaxReceiveCount = 3, Queue = _deadletter } }); _function.AddEventSource(new SqsEventSource(_queue)); }
internal DotnetLambdaDemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // The code that defines your stack goes here // Create S3 Bucket var s3Bucket = new Bucket(this, "demoS3", new BucketProps { BucketName = "serverless-inventory-app-s3-bucket", RemovalPolicy = RemovalPolicy.DESTROY }); // Create Lambda Function for S3 Upload var func_WithCDK = new Function(this, "demoFuncS3", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, FunctionName = "serverless-inventory-app-s3-func", Code = Code.FromAsset("src/func_WithCDK/prod/func_WithCDK"), Handler = "func_WithCDK::func_WithCDK.Function::FunctionHandler" }); // Add Lambda Function S3 Event func_WithCDK.AddEventSource(new S3EventSource(s3Bucket, new S3EventSourceProps { Events = new [] { EventType.OBJECT_CREATED } })); }
internal AwsServerlessStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // Create IAM Admin Role var iamRole = new Role(this, "Role", new RoleProps { RoleName = "LambdaAdminRole", AssumedBy = new ServicePrincipal("lambda.amazonaws.com"), ManagedPolicies = new [] { ManagedPolicy.FromManagedPolicyArn(this, "RolePolicy", "arn:aws:iam::aws:policy/AdministratorAccess") } }); // Create A S3 Bucket var s3Bucket = new Bucket(this, "demoS3", new BucketProps { BucketName = "des-inv-app-s3-bckt", RemovalPolicy = RemovalPolicy.DESTROY, PublicReadAccess = true, }); // Create A DynamoDB var dynamoDBTable = new Table(this, "demoDynamoDB", new TableProps { TableName = "serverless-inventory-app-dynamodb-table", PartitionKey = new Attribute { Name = "Store", Type = AttributeType.STRING }, SortKey = new Attribute { Name = "Item", Type = AttributeType.STRING }, BillingMode = BillingMode.PAY_PER_REQUEST, Stream = StreamViewType.NEW_AND_OLD_IMAGES, RemovalPolicy = RemovalPolicy.DESTROY }); // Create Lambda Function for DynamoDB var func_DynamoDB = new Function(this, "demoFuncDynamoDB", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, FunctionName = "serverless-inventory-app-func-dynamodb", Code = Code.FromAsset("publish_lambda/func_DynamoDB"), Handler = "func_DynamoDB::func_DynamoDB.Function::FunctionHandler", Timeout = Amazon.CDK.Duration.Minutes(3), Role = iamRole, //Role = Role.FromRoleArn (this, "fullAccessLambda_DynamoDB", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { }) }); // Create Lambda Function for SNS var func_SNS = new Function(this, "demoFuncSNS", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, FunctionName = "serverless-inventory-app-func-sns", Code = Code.FromAsset("publish_lambda/func_SNS"), Handler = "func_SNS::func_SNS.Function::FunctionHandler", Timeout = Amazon.CDK.Duration.Minutes(3), Role = iamRole, //Role = Role.FromRoleArn (this, "fullAccessLambda_SNS", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { }) }); // Create Lambda Function for RestAPI var func_GetItems = new Function(this, "demoFuncGetItems", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, FunctionName = "serverless-inventory-app-func-getitems", Code = Code.FromAsset("publish_lambda/func_GetItems"), Handler = "func_GetItems::func_GetItems.Function::FunctionHandler", Timeout = Amazon.CDK.Duration.Minutes(3), Role = iamRole, //Role = Role.FromRoleArn (this, "fullAccessLambda_GetItems", "arn:aws:iam::138340313734:role/Lambda_AdminRole", new FromRoleArnOptions { }) }); // Create API Gateway for Applications var apiGateway = new LambdaRestApi(this, "demoAPIGateway", new LambdaRestApiProps { Handler = func_GetItems, RestApiName = "serverless-inventory-app-api-inventory", Proxy = false, }); var items = apiGateway.Root.AddResource("api"); items.AddMethod("GET"); // Create Lambda Event for Upload Image S3 func_DynamoDB.AddEventSource(new S3EventSource(s3Bucket, new S3EventSourceProps { Events = new [] { EventType.OBJECT_CREATED } })); // Create Lambda Event for Insert DynamoDB func_SNS.AddEventSource(new DynamoEventSource(dynamoDBTable, new DynamoEventSourceProps { StartingPosition = StartingPosition.LATEST, })); // Create A SNS var snsTopic = new Topic(this, "demoSNS", new TopicProps { TopicName = "NoStock", DisplayName = "Out of Stock Topic", }); snsTopic.AddSubscription(new EmailSubscription("*****@*****.**", new EmailSubscriptionProps { })); }
internal ApigwSnsSqsLambdaCdkDotnetStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { var topicCarPriceChange = new Topic(this, "CarPriceChange"); var queueCarChangeQueueNonPremium = new Queue(this, "CarChangeQueueNonPremium", new QueueProps { VisibilityTimeout = Duration.Seconds(300) }); topicCarPriceChange.AddSubscription(new SqsSubscription(queueCarChangeQueueNonPremium)); var lambdaCarChangeQueueNonPremium = new Function(this, "nonPremiumWorkerHandler", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "ApiEventHandler::ApiEventHandler.Function::SQSHandler", Code = Code.FromAsset("./src/lambdaHandler/ApiEventHandler/src/ApiEventHandler/bin/Debug/netcoreapp3.1"), }); lambdaCarChangeQueueNonPremium.AddEventSource(new SqsEventSource(queueCarChangeQueueNonPremium)); var queueCarChangeQueuPremium = new Queue(this, "CarChangeQueuePremium", new QueueProps { VisibilityTimeout = Duration.Seconds(300) }); topicCarPriceChange.AddSubscription(new SqsSubscription(queueCarChangeQueuPremium)); IEnumerable <string?> commands = new[] { "cd /asset-input", "export DOTNET_CLI_HOME=\"/tmp/DOTNET_CLI_HOME\"", "export PATH=\"$PATH:/tmp/DOTNET_CLI_HOME/.dotnet/tools\"", "dotnet tool install -g Amazon.Lambda.Tools", "dotnet lambda package -o output.zip", "unzip -o -d /asset-output output.zip" }; var lambdaCarChangeQueuePremium = new Function(this, "premiumWorkerHandler", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "Lambdas::Lambdas.Function::SQSHandler", Code = Code.FromAsset("./src/lambdaHandler/ApiEventHandler/src/ApiEventHandler", new AssetOptions { Bundling = new BundlingOptions { Image = Runtime.DOTNET_CORE_3_1.BundlingImage, Command = new[] { "bash", "-c", string.Join(" && ", commands) } } }) }); lambdaCarChangeQueuePremium.AddEventSource(new SqsEventSource(queueCarChangeQueuPremium)); var gateWayExecutionRole = new Role(this, "GatewayExecutionRole", new RoleProps { AssumedBy = new ServicePrincipal("apigateway.amazonaws.com"), InlinePolicies = new Dictionary <string, PolicyDocument> { { "PublishMessagePolicy", new PolicyDocument(new PolicyDocumentProps { Statements = new[] { new PolicyStatement(new PolicyStatementProps { Actions = new [] { "sns:Publish" }, Resources = new [] { topicCarPriceChange.TopicArn } }) } }) } } } ); //Api Gateway var awsIntegration = new AwsIntegration(new AwsIntegrationProps { Service = "sns", IntegrationHttpMethod = "POST", Path = "/", Options = new IntegrationOptions { CredentialsRole = gateWayExecutionRole, PassthroughBehavior = PassthroughBehavior.NEVER, RequestParameters = new Dictionary <string, string> { { "integration.request.header.Content-Type", "'application/x-www-form-urlencoded'" } }, RequestTemplates = new Dictionary <string, string> { { "application/json", "Action=Publish&TopicArn=$util.urlEncode('" + topicCarPriceChange.TopicArn + "')&Message=$util.urlEncode($input.body)" } }, IntegrationResponses = new[] { new IntegrationResponse { StatusCode = "200", ResponseTemplates = new Dictionary <string, string> { { "application/json", @"{""status"": ""message added to topic""}" } } }, new IntegrationResponse { StatusCode = "400", SelectionPattern = "^\\[Error\\].*", ResponseTemplates = new Dictionary <string, string> { { "application/json", "{\"state\":\"error\",\"message\":\"$util.escapeJavaScript($input.path('$.errorMessage'))\"}" } } } } }, }); var apiGateWay = new RestApi(this, "CarPriceChangeApi"); apiGateWay.Root.AddMethod("POST", awsIntegration, new MethodOptions { MethodResponses = new[] { new MethodResponse { StatusCode = "200" }, new MethodResponse { StatusCode = "400" } } }); }
internal CensusEtlStack(Construct scope, string id, CensusEtlStackProps props) : base(scope, id, props) { var securityGroup = SecurityGroup.FromSecurityGroupId(this, "aurora-sg", props.AuroraSeucrityGroupId); var censusBucket = Bucket.FromBucketName(this, "lambdaBucket", props.CensusArtifactBucket); var awsManagedLambdaPolicy = ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"); var queue = new Queue(this, "queue", new QueueProps { QueueName = props.CensusEtlQueue }); new CfnOutput(this, "sqs-queue", new CfnOutputProps { ExportName = "enqueueSQS", Value = queue.QueueUrl }); var enqueueRole = new Role(this, "enqueue-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); enqueueRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { censusBucket.BucketArn }, Actions = new string[] { "s3:ListBucket" } })); enqueueRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { queue.QueueArn }, Actions = new string[] { "sqs:SendMessage" } })); enqueueRole.AddManagedPolicy(awsManagedLambdaPolicy); new Function(this, "census-etl", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "EtlEnqueue::EtlEnqueue.Function::FunctionHandler", Code = Code.FromAsset("EtlEnqueue/bin/Debug/netcoreapp3.1/publish"), SecurityGroups = new ISecurityGroup[] { securityGroup }, Role = enqueueRole }); var workerRole = new Role(this, "worker-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); workerRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { censusBucket.BucketArn }, Actions = new string[] { "s3:GetObject" } })); workerRole.AddManagedPolicy(awsManagedLambdaPolicy); workerRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { queue.QueueArn }, Actions = new string[] { "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" } })); var workerFunction = new Function(this, "worker-function", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "something", Code = Code.FromAsset("EtlEnqueue/bin/Debug/netcoreapp3.1/publish"), SecurityGroups = new ISecurityGroup[] { securityGroup }, ReservedConcurrentExecutions = 2, Role = workerRole }); workerFunction.AddEventSource(new SqsEventSource(queue)); }