import * as ecs from '@aws-cdk/aws-ecs' ; import * as alb from '@aws-cdk/aws-elasticloadbalancingv2' ; import * as cdk from '@aws-cdk/core' ; import { Service } from '../service' ; import { ServiceExtension , ServiceBuild } from './extension-interfaces' ; import { Construct } from '@aws-cdk/core' ; export interface HttpLoadBalancerProps { /**
     * The number of ALB requests per target.
     */ readonly requestsPerTarget ? : number ; } /**
 * This extension add a public facing load balancer for sending traffic
 * to one or more replicas of the application container.
 */ export class HttpLoadBalancerExtension extends ServiceExtension { private loadBalancer ! : alb . IApplicationLoadBalancer ; private listener ! : alb . IApplicationListener ; private requestsPerTarget ? : number ; constructor ( props = { } ) { super ( 'load-balancer' ) ; this . requestsPerTarget = props . requestsPerTarget ; } public prehook ( service , scope ) { this . parentService = service ; this . loadBalancer = new alb . ApplicationLoadBalancer ( scope , `${ this . parentService . id }-load-balancer` , { vpc : this . parentService . vpc , internetFacing : true , } ) ; this . listener = this . loadBalancer . addListener ( `${ this . parentService . id }-listener` , { port : 80 , open : true , } ) ; new cdk . CfnOutput ( scope , `${ this . parentService . id }-load-balancer-dns-output` , { value : this . loadBalancer . loadBalancerDnsName , } ) ; } public modifyServiceProps ( props ) { return { ... props , healthCheckGracePeriod : cdk . Duration . minutes ( 1 ) , } as ServiceBuild ; } public useService ( service ) { const targetGroup = this . listener . addTargets ( this . parentService . id , { deregistrationDelay : cdk . Duration . seconds ( 10 ) , port : 80 , targets : [ service ] , } ) ; if ( this . requestsPerTarget ) { if ( ! this . parentService . scalableTaskCount ) { throw Error ( `Auto scaling target for the service '${ this . parentService . id }' hasn't been configured. Please use Service construct to configure 'minTaskCount' and 'maxTaskCount'.` ) ; } this . parentService . scalableTaskCount . scaleOnRequestCount ( `${ this . parentService . id }-target-request-count-${ this . requestsPerTarget }` , { requestsPerTarget : this . requestsPerTarget , targetGroup , } ) ; this . parentService . enableAutoScalingPolicy ( ) ; } } }