aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 15.9 kB
JavaScript
"use strict";var __decorate=exports&&exports.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r},_a,_b;Object.defineProperty(exports,"__esModule",{value:!0}),exports.Canary=exports.ArtifactsEncryptionMode=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},kms=()=>{var tmp=require("../../aws-kms");return kms=()=>tmp,tmp},s3=()=>{var tmp=require("../../aws-s3");return s3=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp},errors_1=()=>{var tmp=require("../../core/lib/errors");return errors_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>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.202.0"};var Cleanup;(function(Cleanup2){Cleanup2.NOTHING="nothing",Cleanup2.LAMBDA="lambda"})(Cleanup||(exports.Cleanup=Cleanup={}));var ArtifactsEncryptionMode;(function(ArtifactsEncryptionMode2){ArtifactsEncryptionMode2.S3_MANAGED="SSE_S3",ArtifactsEncryptionMode2.KMS="SSE_KMS"})(ArtifactsEncryptionMode||(exports.ArtifactsEncryptionMode=ArtifactsEncryptionMode={}));let Canary=class Canary2 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,Canary2),error}if(props.canaryName&&!cdk().Token.isUnresolved(props.canaryName)&&validateName(props.canaryName),super(scope,id,{physicalName:props.canaryName||cdk().Lazy.string({produce:()=>this.generateUniqueName()})}),(0,metadata_resource_1().addConstructMetadata)(this,props),props.cleanup===Cleanup.LAMBDA&&props.provisionedResourceCleanup)throw new(errors_1()).ValidationError("Cannot specify `provisionedResourceCleanup` when `cleanup` is set to `Cleanup.LAMBDA`. Use only `provisionedResourceCleanup`.",this);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({})),this.validateDryRunAndUpdate(props.runtime,props.dryRunAndUpdate);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),artifactConfig:this.createArtifactConfig(props),provisionedResourceCleanup:props.provisionedResourceCleanup!==void 0?props.provisionedResourceCleanup?"AUTOMATIC":"OFF":void 0,dryRunAndUpdate:props.dryRunAndUpdate});this._resource=resource,this.canaryId=resource.attrId,this.canaryState=resource.attrState,this.canaryName=this.getResourceNameAttribute(resource.ref),props.cleanup===Cleanup.LAMBDA&&this.cleanupUnderlyingResources()}validateDryRunAndUpdate(runtime,dryRunAndUpdate){const runtimeName=runtime.name;if(dryRunAndUpdate!==!0||cdk().Token.isUnresolved(runtimeName))return;const RUNTIME_REGEX=/^syn-(nodejs-puppeteer|nodejs-playwright|python-selenium)-(\d+\.\d+)$/,MIN_SUPPORTED_VERSIONS={"nodejs-puppeteer":10,"nodejs-playwright":2,"python-selenium":5.1},match=runtimeName.match(RUNTIME_REGEX);if(!match||match.length<3||MIN_SUPPORTED_VERSIONS[match[1]]===void 0||parseFloat(match[2])<MIN_SUPPORTED_VERSIONS[match[1]])throw new(errors_1()).ValidationError(`dryRunAndUpdate is only supported for canary runtime versions 'syn-nodejs-puppeteer-10.0+', 'syn-nodejs-playwright-2.0+', or 'syn-python-selenium-5.1+', got: ${runtimeName}`,this)}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(errors_1()).ValidationError('Only VPC-associated Canaries have security groups to manage. Supply the "vpc" parameter when creating the Canary.',this);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,props.runtime.name)};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(errors_1()).ValidationError(`Canary Handler must be specified as 'fileName.handler' for legacy runtimes, received ${handler}`,this)}else if(!handler.match(/^([0-9a-zA-Z_-]+\/)*[0-9A-Za-z_\\-]+\.[A-Za-z_][A-Za-z0-9_]*$/))throw new(errors_1()).ValidationError(`Canary Handler must be specified either as 'fileName.handler', 'fileName.functionName', or 'folder/fileName.functionName', received ${handler}`,this);if(handler.length<1||handler.length>128)throw new(errors_1()).ValidationError(`Canary Handler length must be between 1 and 128, received ${handler.length}`,this)}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||!cdk().Token.isUnresolved(props.runtime.name)&&props.runtime.name.includes("playwright")))throw new(errors_1()).ValidationError(`You can only enable active tracing for canaries that use canary runtime version 'syn-nodejs-2.0' or later and are not using the Playwright runtime, got ${props.runtime.name}.`,this);let memoryInMb;if(!cdk().Token.isUnresolved(props.memory)&&props.memory!==void 0){if(memoryInMb=props.memory.toMebibytes(),memoryInMb%64!==0)throw new(errors_1()).ValidationError(`\`memory\` must be a multiple of 64 MiB, got ${memoryInMb} MiB.`,this);if(memoryInMb<960||memoryInMb>3008)throw new(errors_1()).ValidationError(`\`memory\` must be between 960 MiB and 3008 MiB, got ${memoryInMb} MiB.`,this)}let timeoutInSeconds;if(!cdk().Token.isUnresolved(props.timeout)&&props.timeout!==void 0){const timeoutInMillis=props.timeout.toMilliseconds();if(timeoutInMillis%1e3!==0)throw new(errors_1()).ValidationError(`\`timeout\` must be set as an integer representing seconds, got ${timeoutInMillis} milliseconds.`,this);if(timeoutInSeconds=props.timeout.toSeconds(),timeoutInSeconds<3||timeoutInSeconds>840)throw new(errors_1()).ValidationError(`\`timeout\` must be between 3 seconds and 840 seconds, got ${timeoutInSeconds} seconds.`,this)}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(errors_1()).ValidationError("You must provide the 'vpc' prop when using VPC-related properties.",this);return}const{subnetIds}=props.vpc.selectSubnets(props.vpcSubnets);if(subnetIds.length<1)throw new(errors_1()).ValidationError("No matching subnets found in the VPC.",this);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)})}}createArtifactConfig(props){if(!props.artifactS3EncryptionMode&&!props.artifactS3KmsKey)return;const isNodeRuntime=props.runtime.family===runtime_1().RuntimeFamily.NODEJS;if(props.artifactS3EncryptionMode===ArtifactsEncryptionMode.S3_MANAGED&&props.artifactS3KmsKey)throw new(errors_1()).ValidationError(`A customer-managed KMS key was provided, but the encryption mode is not set to SSE-KMS, got: ${props.artifactS3EncryptionMode}.`,this);if(!isNodeRuntime&&props.artifactS3EncryptionMode)throw new(errors_1()).ValidationError(`Artifact encryption is only supported for canaries that use Synthetics runtime version \`syn-nodejs-puppeteer-3.3\` or later and the Playwright runtime, got ${props.runtime.name}.`,this);const encryptionMode=props.artifactS3EncryptionMode?props.artifactS3EncryptionMode:props.artifactS3KmsKey?ArtifactsEncryptionMode.KMS:void 0;let encryptionKey;return encryptionMode===ArtifactsEncryptionMode.KMS&&(encryptionKey=props.artifactS3KmsKey??new(kms()).Key(this,"Key",{description:`Created by ${this.node.path}`})),encryptionKey?.grantEncryptDecrypt(this.role),{s3Encryption:{encryptionMode,kmsKeyArn:encryptionKey?.keyArn}}}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.202.0"},Canary.PROPERTY_INJECTION_ID="aws-cdk-lib.aws-synthetics.Canary",__decorate([(0,metadata_resource_1().MethodMetadata)()],Canary.prototype,"metricDuration",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Canary.prototype,"metricSuccessPercent",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Canary.prototype,"metricFailed",null),exports.Canary=Canary=__decorate([prop_injectable_1().propertyInjectable],Canary);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>255)throw new(errors_1()).UnscopedValidationError(`Canary name is too large, must be between 1 and 255 characters, but is ${name.length} (got "${name}")`);if(!nameRegex.test(name))throw new(errors_1()).UnscopedValidationError(`Canary name must be lowercase, numbers, hyphens, or underscores (got "${name}")`)}