aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 11.3 kB
JavaScript
"use strict";var _a,_b;Object.defineProperty(exports,"__esModule",{value:!0}),exports.Canary=exports.Cleanup=exports.Test=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var crypto=()=>{var tmp=require("crypto");return crypto=()=>tmp,tmp},runtime_1=()=>{var tmp=require("./runtime");return runtime_1=()=>tmp,tmp},synthetics_canned_metrics_generated_1=()=>{var tmp=require("./synthetics-canned-metrics.generated");return synthetics_canned_metrics_generated_1=()=>tmp,tmp},synthetics_generated_1=()=>{var tmp=require("./synthetics.generated");return synthetics_generated_1=()=>tmp,tmp},aws_cloudwatch_1=()=>{var tmp=require("../../aws-cloudwatch");return aws_cloudwatch_1=()=>tmp,tmp},ec2=()=>{var tmp=require("../../aws-ec2");return ec2=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},s3=()=>{var tmp=require("../../aws-s3");return s3=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp},auto_delete_underlying_resources_provider_generated_1=()=>{var tmp=require("../../custom-resource-handlers/dist/aws-synthetics/auto-delete-underlying-resources-provider.generated");return auto_delete_underlying_resources_provider_generated_1=()=>tmp,tmp};const AUTO_DELETE_UNDERLYING_RESOURCES_RESOURCE_TYPE="Custom::SyntheticsAutoDeleteUnderlyingResources",AUTO_DELETE_UNDERLYING_RESOURCES_TAG="aws-cdk:auto-delete-underlying-resources";class Test{static custom(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_synthetics_CustomTestOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.custom),error}return new Test(options.code,options.handler)}constructor(code,handler){this.code=code,this.handler=handler}}exports.Test=Test,_a=JSII_RTTI_SYMBOL_1,Test[_a]={fqn:"aws-cdk-lib.aws_synthetics.Test",version:"2.160.0"};var Cleanup;(function(Cleanup2){Cleanup2.NOTHING="nothing",Cleanup2.LAMBDA="lambda"})(Cleanup||(exports.Cleanup=Cleanup={}));class Canary extends cdk().Resource{constructor(scope,id,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_synthetics_CanaryProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Canary),error}props.canaryName&&!cdk().Token.isUnresolved(props.canaryName)&&validateName(props.canaryName),super(scope,id,{physicalName:props.canaryName||cdk().Lazy.string({produce:()=>this.generateUniqueName()})}),this.artifactsBucket=props.artifactsBucketLocation?.bucket??new(s3()).Bucket(this,"ArtifactsBucket",{encryption:s3().BucketEncryption.KMS_MANAGED,enforceSSL:!0,lifecycleRules:props.artifactsBucketLifecycleRules}),this.role=props.role??this.createDefaultRole(props),props.vpc&&(this._connections=new(ec2()).Connections({}));const resource=new(synthetics_generated_1()).CfnCanary(this,"Resource",{artifactS3Location:this.artifactsBucket.s3UrlForObject(props.artifactsBucketLocation?.prefix),executionRoleArn:this.role.roleArn,startCanaryAfterCreation:props.startAfterCreation??!0,runtimeVersion:props.runtime.name,name:this.physicalName,schedule:this.createSchedule(props),failureRetentionPeriod:props.failureRetentionPeriod?.toDays(),successRetentionPeriod:props.successRetentionPeriod?.toDays(),code:this.createCode(props),runConfig:this.createRunConfig(props),vpcConfig:this.createVpcConfig(props)});this._resource=resource,this.canaryId=resource.attrId,this.canaryState=resource.attrState,this.canaryName=this.getResourceNameAttribute(resource.ref),props.cleanup===Cleanup.LAMBDA&&this.cleanupUnderlyingResources()}cleanupUnderlyingResources(){const provider=auto_delete_underlying_resources_provider_generated_1().AutoDeleteUnderlyingResourcesProvider.getOrCreateProvider(this,AUTO_DELETE_UNDERLYING_RESOURCES_RESOURCE_TYPE,{useCfnResponseWrapper:!1,description:`Lambda function for auto-deleting underlying resources created by ${this.canaryName}.`,policyStatements:[{Effect:"Allow",Action:["lambda:DeleteFunction"],Resource:this.lambdaArn()},{Effect:"Allow",Action:["synthetics:GetCanary"],Resource:"*"}]});new(cdk()).CustomResource(this,"AutoDeleteUnderlyingResourcesCustomResource",{resourceType:AUTO_DELETE_UNDERLYING_RESOURCES_RESOURCE_TYPE,serviceToken:provider.serviceToken,properties:{CanaryName:this.canaryName}}),cdk().Tags.of(this._resource).add(AUTO_DELETE_UNDERLYING_RESOURCES_TAG,"true")}get connections(){if(!this._connections)throw new Error('Only VPC-associated Canaries have security groups to manage. Supply the "vpc" parameter when creating the Canary.');return this._connections}metricDuration(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricDuration),error}return new(aws_cloudwatch_1()).Metric({...synthetics_canned_metrics_generated_1().CloudWatchSyntheticsMetrics.durationMaximum({CanaryName:this.canaryName}),statistic:"Average",...options}).attachTo(this)}metricSuccessPercent(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricSuccessPercent),error}return this.cannedMetric(synthetics_canned_metrics_generated_1().CloudWatchSyntheticsMetrics.successPercentAverage,options)}metricFailed(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricFailed),error}return this.cannedMetric(synthetics_canned_metrics_generated_1().CloudWatchSyntheticsMetrics.failedSum,options)}createDefaultRole(props){const prefix=props.artifactsBucketLocation?.prefix,policy=new(iam()).PolicyDocument({statements:[new(iam()).PolicyStatement({resources:["*"],actions:["s3:ListAllMyBuckets"]}),new(iam()).PolicyStatement({resources:[this.artifactsBucket.bucketArn],actions:["s3:GetBucketLocation"]}),new(iam()).PolicyStatement({resources:[this.artifactsBucket.arnForObjects(`${prefix?prefix+"/*":"*"}`)],actions:["s3:PutObject"]}),new(iam()).PolicyStatement({resources:["*"],actions:["cloudwatch:PutMetricData"],conditions:{StringEquals:{"cloudwatch:namespace":"CloudWatchSynthetics"}}}),new(iam()).PolicyStatement({resources:[this.logGroupArn()],actions:["logs:CreateLogStream","logs:CreateLogGroup","logs:PutLogEvents"]})]}),managedPolicies=[];return props.vpc&&managedPolicies.push(iam().ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole")),new(iam()).Role(this,"ServiceRole",{assumedBy:new(iam()).ServicePrincipal("lambda.amazonaws.com"),inlinePolicies:{canaryPolicy:policy},managedPolicies})}logGroupArn(){return cdk().Stack.of(this).formatArn({service:"logs",resource:"log-group",arnFormat:cdk().ArnFormat.COLON_RESOURCE_NAME,resourceName:"/aws/lambda/cwsyn-*"})}lambdaArn(){return cdk().Stack.of(this).formatArn({service:"lambda",resource:"function",arnFormat:cdk().ArnFormat.COLON_RESOURCE_NAME,resourceName:"cwsyn-*"})}createCode(props){this.validateHandler(props.test.handler,props.runtime);const codeConfig={handler:props.test.handler,...props.test.code.bind(this,props.test.handler,props.runtime.family)};return{handler:codeConfig.handler,script:codeConfig.inlineCode,s3Bucket:codeConfig.s3Location?.bucketName,s3Key:codeConfig.s3Location?.objectKey,s3ObjectVersion:codeConfig.s3Location?.objectVersion}}validateHandler(handler,runtime){if([runtime_1().Runtime.SYNTHETICS_PYTHON_SELENIUM_1_0].includes(runtime)){if(!handler.match(/^[0-9A-Za-z_\\-]+\.handler*$/))throw new Error(`Canary Handler must be specified as 'fileName.handler' for legacy runtimes, received ${handler}`)}else if(!handler.match(/^([0-9a-zA-Z_-]+\/)*[0-9A-Za-z_\\-]+\.[A-Za-z_][A-Za-z0-9_]*$/))throw new Error(`Canary Handler must be specified either as 'fileName.handler', 'fileName.functionName', or 'folder/fileName.functionName', received ${handler}`);if(handler.length<1||handler.length>128)throw new Error(`Canary Handler length must be between 1 and 128, received ${handler.length}`)}createRunConfig(props){if(props.activeTracing===void 0&&!props.environmentVariables&&!props.memory&&!props.timeout)return;if(props.activeTracing&&!cdk().Token.isUnresolved(props.runtime.family)&&props.runtime.family!==runtime_1().RuntimeFamily.NODEJS)throw new Error("You can only enable active tracing for canaries that use canary runtime version `syn-nodejs-2.0` or later.");let memoryInMb;if(!cdk().Token.isUnresolved(props.memory)&&props.memory!==void 0){if(memoryInMb=props.memory.toMebibytes(),memoryInMb%64!==0)throw new Error(`\`memory\` must be a multiple of 64 MiB, got ${memoryInMb} MiB.`);if(memoryInMb<960||memoryInMb>3008)throw new Error(`\`memory\` must be between 960 MiB and 3008 MiB, got ${memoryInMb} MiB.`)}let timeoutInSeconds;if(!cdk().Token.isUnresolved(props.timeout)&&props.timeout!==void 0){const timeoutInMillis=props.timeout.toMilliseconds();if(timeoutInMillis%1e3!==0)throw new Error(`\`timeout\` must be set as an integer representing seconds, got ${timeoutInMillis} milliseconds.`);if(timeoutInSeconds=props.timeout.toSeconds(),timeoutInSeconds<3||timeoutInSeconds>840)throw new Error(`\`timeout\` must be between 3 seconds and 840 seconds, got ${timeoutInSeconds} seconds.`)}return{activeTracing:props.activeTracing,environmentVariables:props.environmentVariables,memoryInMb,timeoutInSeconds}}createSchedule(props){return{durationInSeconds:`${props.timeToLive?.toSeconds()??0}`,expression:props.schedule?.expressionString??"rate(5 minutes)"}}createVpcConfig(props){if(!props.vpc){if(props.vpcSubnets!=null||props.securityGroups!=null)throw new Error("You must provide the 'vpc' prop when using VPC-related properties.");return}const{subnetIds}=props.vpc.selectSubnets(props.vpcSubnets);if(subnetIds.length<1)throw new Error("No matching subnets found in the VPC.");let securityGroups;return props.securityGroups&&props.securityGroups.length>0?securityGroups=props.securityGroups:securityGroups=[new(ec2()).SecurityGroup(this,"SecurityGroup",{vpc:props.vpc,description:"Automatic security group for Canary "+cdk().Names.uniqueId(this)})],this._connections.addSecurityGroup(...securityGroups),{vpcId:props.vpc.vpcId,subnetIds,securityGroupIds:cdk().Lazy.list({produce:()=>this.connections.securityGroups.map(sg=>sg.securityGroupId)})}}generateUniqueName(){const name=cdk().Names.uniqueId(this).toLowerCase().replace(" ","-");return name.length<=21?name:name.substring(0,15)+nameHash(name)}cannedMetric(fn,props){return new(aws_cloudwatch_1()).Metric({...fn({CanaryName:this.canaryName}),...props}).attachTo(this)}}exports.Canary=Canary,_b=JSII_RTTI_SYMBOL_1,Canary[_b]={fqn:"aws-cdk-lib.aws_synthetics.Canary",version:"2.160.0"};function nameHash(name){return crypto().createHash("sha256").update(name).digest("hex").slice(0,6)}const nameRegex=/^[0-9a-z_\-]+$/;function validateName(name){if(name.length>21)throw new Error(`Canary name is too large, must be between 1 and 21 characters, but is ${name.length} (got "${name}")`);if(!nameRegex.test(name))throw new Error(`Canary name must be lowercase, numbers, hyphens, or underscores (got "${name}")`)}