import envVars from "../../config/env" ; import { Consumer , SQSMessage } from "sqs-consumer" ; import EventEmitter from "events" ; import { getLogger } from "../../config/logger" ; const logger = getLogger ( "micros.lifecycle" ) ; let client ; const eventEmitter = new EventEmitter ( ) ; export const listenToMicrosLifecycle = ( active , inactive ) : void => { eventEmitter . on ( "active" , active ) ; eventEmitter . on ( "inactive" , inactive ) ; if ( ( active || inactive ) && ! client ) { if ( ! envVars . SNS_NOTIFICATION_LIFECYCLE_QUEUE_URL ) { const msg = "Missing 'SNS_NOTIFICATION_LIFECYCLE_QUEUE_URL' environment variable for Micros Lifecycle Events." ; logger . error ( msg ) ; throw new Error ( msg ) ; } client = Consumer . create ( { queueUrl : envVars . SNS_NOTIFICATION_LIFECYCLE_QUEUE_URL , region : envVars . SNS_NOTIFICATION_LIFECYCLE_QUEUE_REGION , handleMessage : async ( data ) => { logger . debug ( data , "Received Micros event" ) ; if ( ! data . Body ) { logger . debug ( "Lifecycle event missing body, skipping." ) ; return ; } try { const lifecycleData = JSON . parse ( data . Body ) ; if ( lifecycleData . Subject === "Micros Lifecycle Notification" ) { logger . info ( data , "Received Micros lifecycle event" ) ; const notification = JSON . parse ( lifecycleData . Message ) ; const event = notification . LifecycleTransition ?. toLowerCase ( ) . replace ( "micros:" , "" ) ; if ( event ) { logger . info ( { event , data : notification } , `Triggering '${ event }' lifecycle event` ) ; eventEmitter . emit ( event , notification ) ; } } } catch ( err ) { logger . error ( err , "Could not parsed JSON data from Micros Lifecycle SQS queue." ) ; } } } ) ; client . start ( ) ; } } ; type Callback = ( data : LifecycleMessageData ) => void ; interface LifecycleData { Type : string ; Subject : string ; Message : string ; } interface LifecycleMessageData { EC2InstanceId : string ; LifecycleTransition : "micros:ACTIVE" | "micros:INACTIVE" ; TrafficPercentage ? : number ; }