"""Handler.""" from vector_utils import queries from vector_utils.aws_utils import sqs from vector_utils.datadog.metrics import call_datadog_with_metric as _call_dd from src import config from src.logger import get_current_logger class InvocationContext: """This is for passing around the invoke context to logger.""" correlation_id = None READY_TO_CLOSE_STATUS = 'ready_to_close' QUEUED_FOR_CLOSING_STATUS = 'queued_for_closing' def handler(event, context): """Entrypoint to Lambda function. Args: event (optional): AWS Lambda event dependent structure with metadata. context (LambdaContext): AWS Lambda context. """ InvocationContext.correlation_id = context.aws_request_id log = get_current_logger(InvocationContext.correlation_id) log.info('Starting find batch to close.') log.info(f'Send datadog metric - {config.DATADOG_ATTEMPT}.') call_datadog_with_metric(config.DATADOG_ATTEMPT) log.info('Call sp_get_next_batch_to_close.') results = queries.get_batches_to_close( conn_info=config.DD_MYSQL_CONN_INFO) log.info('About to process {} batch_ids with {} status'.format( len(results), READY_TO_CLOSE_STATUS)) queue_name = config.CLOSE_BATCH_QUEUE_NAME for batch in results: batch_id = batch['delivery_batch_id'] r = queries.update_batch_status( READY_TO_CLOSE_STATUS, QUEUED_FOR_CLOSING_STATUS, batch_id, conn_info=config.DD_MYSQL_CONN_INFO) if r: log.info('Updated batch_id {} to {}'.format( batch_id, QUEUED_FOR_CLOSING_STATUS)) sqs.add_message_to_sqs( queue_name, {'batch_id': batch_id}) log.info('Added batch_id {} to {} queue'.format( batch_id, queue_name)) call_datadog_with_metric(config.DATADOG_DB_SUCCESS) else: log.info('Failed to update batch_id {} to {}'.format( batch_id, QUEUED_FOR_CLOSING_STATUS)) call_datadog_with_metric(config.DATADOG_DB_FAILURE) else: log.info('No open batch found ready to be closed.') def call_datadog_with_metric(metric): """Call datadog with metric. Args: metric (str): custom metric name to send to DataDog. """ _call_dd( f'{config.DATADOG_SCRIPT_NAME}.{metric}', [ f'environment:{config.ENVIRONMENT}' ], api_key=config.DATADOG_API_KEY, app_key=config.DATADOG_APP_KEY, logger=get_current_logger(InvocationContext.correlation_id) ) if __name__ == '__main__': handler(None, None)