UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

2 lines (1 loc) 16.4 kB
"use strict";var __classPrivateFieldSet=exports&&exports.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state=="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value},__classPrivateFieldGet=exports&&exports.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state=="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)},_Metric_stackAccount,_Metric_stackRegion,_Metric_accountOverride,_Metric_regionOverride,_a,_b;Object.defineProperty(exports,"__esModule",{value:!0}),exports.MathExpression=exports.Metric=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var alarm_1=()=>{var tmp=require("./alarm");return alarm_1=()=>tmp,tmp},metric_util_1=()=>{var tmp=require("./private/metric-util");return metric_util_1=()=>tmp,tmp},statistic_1=()=>{var tmp=require("./private/statistic");return statistic_1=()=>tmp,tmp},stats_1=()=>{var tmp=require("./stats");return stats_1=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},cdk=()=>{var tmp=require("../../core");return cdk=()=>tmp,tmp},make_enumerable_1=()=>{var tmp=require("./private/make-enumerable");return make_enumerable_1=()=>tmp,tmp};class Metric{static grantPutMetricData(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantPutMetricData),error}return iam().Grant.addToPrincipal({grantee,actions:["cloudwatch:PutMetricData"],resourceArns:["*"]})}constructor(props){_Metric_stackAccount.set(this,void 0),_Metric_stackRegion.set(this,void 0),_Metric_accountOverride.set(this,void 0),_Metric_regionOverride.set(this,void 0);try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Metric),error}this.period=props.period||cdk().Duration.minutes(5);const periodSec=this.period.toSeconds();if(periodSec!==1&&periodSec!==5&&periodSec!==10&&periodSec!==30&&periodSec%60!==0)throw new(cdk()).UnscopedValidationError(`'period' must be 1, 5, 10, 30, or a multiple of 60 seconds, received ${periodSec}`);this.warnings=void 0,this.dimensions=this.validateDimensions(props.dimensionsMap??props.dimensions),this.namespace=props.namespace,this.metricName=props.metricName;const parsedStat=(0,statistic_1().parseStatistic)(props.statistic||stats_1().Stats.AVERAGE);if(parsedStat.type==="generic"){const label=props.label?`, label "${props.label}"`:"",warning=`Unrecognized statistic "${props.statistic}" for metric with namespace "${props.namespace}"${label} and metric name "${props.metricName}". Preferably use the \`aws_cloudwatch.Stats\` helper class to specify a statistic. You can ignore this warning if your statistic is valid but not yet supported by the \`aws_cloudwatch.Stats\` helper class.`;this.warningsV2={"CloudWatch:Alarm:UnrecognizedStatistic":warning},this.warnings=[warning]}this.statistic=(0,statistic_1().normalizeStatistic)(parsedStat),this.label=props.label,this.color=props.color,this.unit=props.unit,__classPrivateFieldSet(this,_Metric_accountOverride,props.account,"f"),__classPrivateFieldSet(this,_Metric_regionOverride,props.region,"f"),__classPrivateFieldSet(this,_Metric_stackAccount,props.stackAccount,"f"),__classPrivateFieldSet(this,_Metric_stackRegion,props.stackRegion,"f"),(0,make_enumerable_1().makeEnumerable)(Metric.prototype,this,"account"),(0,make_enumerable_1().makeEnumerable)(Metric.prototype,this,"region")}with(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.with),error}return(props.label===void 0||props.label===this.label)&&(props.color===void 0||props.color===this.color)&&(props.statistic===void 0||props.statistic===this.statistic)&&(props.unit===void 0||props.unit===this.unit)&&(props.account===void 0||props.account===__classPrivateFieldGet(this,_Metric_accountOverride,"f"))&&(props.region===void 0||props.region===__classPrivateFieldGet(this,_Metric_regionOverride,"f"))&&(props.stackAccount===void 0||props.stackAccount===__classPrivateFieldGet(this,_Metric_stackAccount,"f"))&&(props.stackRegion===void 0||props.stackRegion===__classPrivateFieldGet(this,_Metric_stackRegion,"f"))&&props.dimensions===void 0&&props.dimensionsMap===void 0&&(props.period===void 0||props.period.toSeconds()===this.period.toSeconds())?this:new Metric({dimensionsMap:props.dimensionsMap??props.dimensions??this.dimensions,namespace:this.namespace,metricName:this.metricName,period:ifUndefined(props.period,this.period),statistic:ifUndefined(props.statistic,this.statistic),unit:ifUndefined(props.unit,this.unit),label:ifUndefined(props.label,this.label),color:ifUndefined(props.color,this.color),account:ifUndefined(props.account,__classPrivateFieldGet(this,_Metric_accountOverride,"f")),region:ifUndefined(props.region,__classPrivateFieldGet(this,_Metric_regionOverride,"f")),stackAccount:ifUndefined(props.stackAccount,__classPrivateFieldGet(this,_Metric_stackAccount,"f")),stackRegion:ifUndefined(props.stackRegion,__classPrivateFieldGet(this,_Metric_stackRegion,"f"))})}attachTo(scope){const stack=cdk().Stack.of(scope);return this.with({stackAccount:cdk().Token.isUnresolved(stack.account)?void 0:stack.account,stackRegion:cdk().Token.isUnresolved(stack.region)?void 0:stack.region})}get account(){return __classPrivateFieldGet(this,_Metric_accountOverride,"f")||__classPrivateFieldGet(this,_Metric_stackAccount,"f")}get region(){return __classPrivateFieldGet(this,_Metric_regionOverride,"f")||__classPrivateFieldGet(this,_Metric_stackRegion,"f")}toMetricConfig(){const dims=this.dimensionsAsList();return{metricStat:{dimensions:dims.length>0?dims:void 0,namespace:this.namespace,metricName:this.metricName,period:this.period,statistic:this.statistic,unitFilter:this.unit,account:this.account,region:this.region,accountOverride:__classPrivateFieldGet(this,_Metric_accountOverride,"f"),regionOverride:__classPrivateFieldGet(this,_Metric_regionOverride,"f")},renderingProperties:{color:this.color,label:this.label}}}toAlarmConfig(){const metricConfig=this.toMetricConfig();if(metricConfig.metricStat===void 0)throw new(cdk()).UnscopedValidationError("Using a math expression is not supported here. Pass a 'Metric' object instead");const parsed=(0,statistic_1().parseStatistic)(metricConfig.metricStat.statistic);let extendedStatistic;return parsed.type==="single"?extendedStatistic=(0,statistic_1().singleStatisticToString)(parsed):parsed.type==="pair"&&(extendedStatistic=(0,statistic_1().pairStatisticToString)(parsed)),{dimensions:metricConfig.metricStat.dimensions,namespace:metricConfig.metricStat.namespace,metricName:metricConfig.metricStat.metricName,period:metricConfig.metricStat.period.toSeconds(),statistic:parsed.type==="simple"?parsed.statistic:void 0,extendedStatistic,unit:this.unit}}toGraphConfig(){const metricConfig=this.toMetricConfig();if(metricConfig.metricStat===void 0)throw new(cdk()).UnscopedValidationError("Using a math expression is not supported here. Pass a 'Metric' object instead");return{dimensions:metricConfig.metricStat.dimensions,namespace:metricConfig.metricStat.namespace,metricName:metricConfig.metricStat.metricName,renderingProperties:{period:metricConfig.metricStat.period.toSeconds(),stat:metricConfig.metricStat.statistic,color:asString(metricConfig.renderingProperties?.color),label:asString(metricConfig.renderingProperties?.label)},period:metricConfig.metricStat.period.toSeconds(),statistic:metricConfig.metricStat.statistic,color:asString(metricConfig.renderingProperties?.color),label:asString(metricConfig.renderingProperties?.label),unit:this.unit}}createAlarm(scope,id,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_CreateAlarmOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.createAlarm),error}return new(alarm_1()).Alarm(scope,id,{metric:this.with({statistic:props.statistic,period:props.period}),alarmName:props.alarmName,alarmDescription:props.alarmDescription,comparisonOperator:props.comparisonOperator,datapointsToAlarm:props.datapointsToAlarm,threshold:props.threshold,evaluationPeriods:props.evaluationPeriods,evaluateLowSampleCountPercentile:props.evaluateLowSampleCountPercentile,treatMissingData:props.treatMissingData,actionsEnabled:props.actionsEnabled})}toString(){return this.label||this.metricName}dimensionsAsList(){const dims=this.dimensions;return dims===void 0?[]:Object.keys(dims).sort().map(key=>({name:key,value:dims[key]}))}validateDimensions(dims){if(!dims)return dims;var dimsArray=Object.keys(dims);if(dimsArray?.length>30)throw new(cdk()).UnscopedValidationError(`The maximum number of dimensions is 30, received ${dimsArray.length}`);return dimsArray.map(key=>{if(dims[key]===void 0||dims[key]===null)throw new(cdk()).UnscopedValidationError(`Dimension value of '${dims[key]}' is invalid`);if(key.length<1||key.length>255)throw new(cdk()).UnscopedValidationError(`Dimension name must be at least 1 and no more than 255 characters; received ${key}`);if(dims[key].length<1||dims[key].length>255)throw new(cdk()).UnscopedValidationError(`Dimension value must be at least 1 and no more than 255 characters; received ${dims[key]}`)}),dims}}exports.Metric=Metric,_Metric_stackAccount=new WeakMap,_Metric_stackRegion=new WeakMap,_Metric_accountOverride=new WeakMap,_Metric_regionOverride=new WeakMap,_a=JSII_RTTI_SYMBOL_1,Metric[_a]={fqn:"aws-cdk-lib.aws_cloudwatch.Metric",version:"2.185.0"};function asString(x){if(x!==void 0){if(typeof x!="string")throw new(cdk()).UnscopedValidationError(`Expected string, got ${x}`);return x}}class MathExpression{constructor(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MathExpressionProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,MathExpression),error}this.period=props.period||cdk().Duration.minutes(5),this.expression=props.expression,this.label=props.label,this.color=props.color,this.searchAccount=props.searchAccount,this.searchRegion=props.searchRegion;const{record,overridden}=changeAllPeriods(props.usingMetrics??{},this.period);this.usingMetrics=record;const warnings={};overridden&&(warnings["CloudWatch:Math:MetricsPeriodsOverridden"]=`Periods of metrics in 'usingMetrics' for Math expression '${this.expression}' have been overridden to ${this.period.toSeconds()} seconds.`);const invalidVariableNames=Object.keys(this.usingMetrics).filter(x=>!validVariableName(x));if(invalidVariableNames.length>0)throw new(cdk()).UnscopedValidationError(`Invalid variable names in expression: ${invalidVariableNames}. Must start with lowercase letter and only contain alphanumerics.`);this.validateNoIdConflicts();const missingIdentifiers=allIdentifiersInExpression(this.expression).filter(i=>!this.usingMetrics[i]);!this.expression.toUpperCase().match("\\b(INSIGHT_RULE_METRIC|SELECT|SEARCH|METRICS)\\b")&&missingIdentifiers.length>0&&(warnings["CloudWatch:Math:UnknownIdentifier"]=`Math expression '${this.expression}' references unknown identifiers: ${missingIdentifiers.join(", ")}. Please add them to the 'usingMetrics' map.`);for(const m of Object.values(this.usingMetrics))for(const[id,message]of Object.entries(m.warningsV2??{}))warnings[id]=message;Object.keys(warnings).length>0&&(this.warnings=Array.from(Object.values(warnings)),this.warningsV2=warnings)}with(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MathExpressionOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.with),error}return(props.label===void 0||props.label===this.label)&&(props.color===void 0||props.color===this.color)&&(props.period===void 0||props.period.toSeconds()===this.period.toSeconds())&&(props.searchAccount===void 0||props.searchAccount===this.searchAccount)&&(props.searchRegion===void 0||props.searchRegion===this.searchRegion)?this:new MathExpression({expression:this.expression,usingMetrics:this.usingMetrics,label:ifUndefined(props.label,this.label),color:ifUndefined(props.color,this.color),period:ifUndefined(props.period,this.period),searchAccount:ifUndefined(props.searchAccount,this.searchAccount),searchRegion:ifUndefined(props.searchRegion,this.searchRegion)})}toAlarmConfig(){throw new(cdk()).UnscopedValidationError("Using a math expression is not supported here. Pass a 'Metric' object instead")}toGraphConfig(){throw new(cdk()).UnscopedValidationError("Using a math expression is not supported here. Pass a 'Metric' object instead")}toMetricConfig(){return{mathExpression:{period:this.period.toSeconds(),expression:this.expression,usingMetrics:this.usingMetrics,searchAccount:this.searchAccount,searchRegion:this.searchRegion},renderingProperties:{label:this.label,color:this.color}}}createAlarm(scope,id,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_CreateAlarmOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.createAlarm),error}return new(alarm_1()).Alarm(scope,id,{metric:this.with({period:props.period}),alarmName:props.alarmName,alarmDescription:props.alarmDescription,comparisonOperator:props.comparisonOperator,datapointsToAlarm:props.datapointsToAlarm,threshold:props.threshold,evaluationPeriods:props.evaluationPeriods,evaluateLowSampleCountPercentile:props.evaluateLowSampleCountPercentile,treatMissingData:props.treatMissingData,actionsEnabled:props.actionsEnabled})}toString(){return this.label||this.expression}validateNoIdConflicts(){const seen=new Map;visit(this);function visit(metric){(0,metric_util_1().dispatchMetric)(metric,{withStat(){},withExpression(expr){for(const[id,subMetric]of Object.entries(expr.usingMetrics)){const existing=seen.get(id);if(existing&&(0,metric_util_1().metricKey)(existing)!==(0,metric_util_1().metricKey)(subMetric))throw new(cdk()).UnscopedValidationError(`The ID '${id}' used for two metrics in the expression: '${subMetric}' and '${existing}'. Rename one.`);seen.set(id,subMetric),visit(subMetric)}}})}}}exports.MathExpression=MathExpression,_b=JSII_RTTI_SYMBOL_1,MathExpression[_b]={fqn:"aws-cdk-lib.aws_cloudwatch.MathExpression",version:"2.185.0"};const VARIABLE_PAT="[a-z][a-zA-Z0-9_]*",VALID_VARIABLE=new RegExp(`^${VARIABLE_PAT}$`),FIND_VARIABLE=new RegExp(VARIABLE_PAT,"g");function validVariableName(x){return VALID_VARIABLE.test(x)}function allIdentifiersInExpression(x){return Array.from(matchAll(x,FIND_VARIABLE)).map(m=>m[0])}function ifUndefined(x,def){return x!==void 0?x:def}function changeAllPeriods(metrics,period){const retRecord={};let retOverridden=!1;for(const[id,m]of Object.entries(metrics)){const{metric,overridden}=changePeriod(m,period);retRecord[id]=metric,overridden&&(retOverridden=!0)}return{record:retRecord,overridden:retOverridden}}function changePeriod(metric,period){if(isModifiableMetric(metric)){const overridden=isMetricWithPeriod(metric)&&metric.period.toSeconds()!==cdk().Duration.minutes(5).toSeconds()&&metric.period.toSeconds()!==period.toSeconds();return{metric:metric.with({period}),overridden}}throw new(cdk()).UnscopedValidationError(`Metric object should also implement 'with': ${metric}`)}function isModifiableMetric(m){return typeof m=="object"&&m!==null&&!!m.with}function isMetricWithPeriod(m){return typeof m=="object"&&m!==null&&!!m.period}function matchAll(x,re){const ret=new Array;let m;for(;m=re.exec(x);)ret.push(m);return ret}