UNPKG

aws-cdk-lib

Version:

Version 2 of the AWS Cloud Development Kit library

2 lines (1 loc) 3.84 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.handler=void 0;const Logs=require("@aws-sdk/client-cloudwatch-logs");async function createLogGroupSafe(logGroupName,client,withDelay){await withDelay(async()=>{try{const params={logGroupName},command=new Logs.CreateLogGroupCommand(params);await client.send(command)}catch(error){if(error.name==="ResourceAlreadyExistsException")return;throw error}})}async function deleteLogGroup(logGroupName,client,withDelay){await withDelay(async()=>{try{const params={logGroupName},command=new Logs.DeleteLogGroupCommand(params);await client.send(command)}catch(error){if(error.name==="ResourceNotFoundException")return;throw error}})}async function setRetentionPolicy(logGroupName,client,withDelay,retentionInDays){await withDelay(async()=>{if(retentionInDays){const params={logGroupName,retentionInDays},putCommand=new Logs.PutRetentionPolicyCommand(params);await client.send(putCommand)}else{const params={logGroupName},deleteCommand=new Logs.DeleteRetentionPolicyCommand(params);await client.send(deleteCommand)}})}async function handler(event,context){try{console.log(JSON.stringify({...event,ResponseURL:"..."}));const logGroupName=event.ResourceProperties.LogGroupName,logGroupRegion=event.ResourceProperties.LogGroupRegion,maxRetries=parseIntOptional(event.ResourceProperties.SdkRetry?.maxRetries)??5,withDelay=makeWithDelay(maxRetries),sdkConfig={logger:console,region:logGroupRegion,maxAttempts:Math.max(5,maxRetries)},client=new Logs.CloudWatchLogsClient(sdkConfig);if((event.RequestType==="Create"||event.RequestType==="Update")&&(await createLogGroupSafe(logGroupName,client,withDelay),await setRetentionPolicy(logGroupName,client,withDelay,parseIntOptional(event.ResourceProperties.RetentionInDays)),event.RequestType==="Create")){const clientForCustomResourceFunction=new Logs.CloudWatchLogsClient({logger:console,region:process.env.AWS_REGION});await createLogGroupSafe(`/aws/lambda/${context.functionName}`,clientForCustomResourceFunction,withDelay),await setRetentionPolicy(`/aws/lambda/${context.functionName}`,clientForCustomResourceFunction,withDelay,1)}event.RequestType==="Delete"&&event.ResourceProperties.RemovalPolicy==="destroy"&&await deleteLogGroup(logGroupName,client,withDelay),await respond("SUCCESS","OK",logGroupName)}catch(e){console.log(e),await respond("FAILED",e.message,event.ResourceProperties.LogGroupName)}function respond(responseStatus,reason,physicalResourceId){const responseBody=JSON.stringify({Status:responseStatus,Reason:reason,PhysicalResourceId:physicalResourceId,StackId:event.StackId,RequestId:event.RequestId,LogicalResourceId:event.LogicalResourceId,Data:{LogGroupName:event.ResourceProperties.LogGroupName}});console.log("Responding",responseBody);const parsedUrl=require("url").parse(event.ResponseURL),requestOptions={hostname:parsedUrl.hostname,path:parsedUrl.path,method:"PUT",headers:{"content-type":"","content-length":Buffer.byteLength(responseBody,"utf8")}};return new Promise((resolve,reject)=>{try{const request=require("https").request(requestOptions,resolve);request.on("error",reject),request.write(responseBody),request.end()}catch(e){reject(e)}})}}exports.handler=handler;function parseIntOptional(value,base=10){if(value!==void 0)return parseInt(value,base)}function makeWithDelay(maxRetries,delayBase=100,delayCap=10*1e3){return async block=>{let attempts=0;do try{return await block()}catch(error){if(error.name==="OperationAbortedException"||error.name==="ThrottlingException")if(attempts<maxRetries){attempts++,await new Promise(resolve=>setTimeout(resolve,calculateDelay(attempts,delayBase,delayCap)));continue}else throw new Error("Out of attempts to change log group");throw error}while(!0)}}function calculateDelay(attempt,base,cap){return Math.round(Math.random()*Math.min(cap,base*2**attempt))}