"""Lambda function module. Handle save to dd db lambda errors, save info about failed sync orders process to specific sql table. """ import datetime import json import sqlalchemy import common_config from connectors import sentry from connectors import vector_obtain_orders from constants import common_fields from constants import const from constants import fields import exceptions import sql_queries import util def save_to_vo_sync_errors(order_dict, error_message, error_timestamp): """Save a new error message to vo_sync_errors. Args: order_dict (dict): vector order data error_message (str): sync error message error_timestamp (datetime): sns event timestamp """ order_id = order_dict[common_fields.VO_ORDER_ID] common_config.logger.debug('Saving error record for order: %s', order_id) with vector_obtain_orders.session_scope() as session: session.execute( sqlalchemy.text(sql_queries.INSERT_ENCODING_QUEUE_DETAIL), {'vector_order_id': order_id, 'error_msg': error_message, 'error_timestamp': error_timestamp}) def handle_record(record): """Process one sns message. Args: record (dict): sns part of message data """ common_config.logger.debug('Reading error record %s', record) # exception details attributes = record[fields.EVENT_RECORD_SNS_ATTRIBUTES] # input params of a crushed lambda as a str event = record[fields.EVENT_RECORD_SNS_MESSAGE] common_config.logger.debug('Loading event json %s', event) order_aws_dict = json.loads(event) order_dict = util.parse_aws_dict(order_aws_dict) error_dict = attributes[fields.EVENT_RECORD_SNS_ATTRIBUTES_ERROR] error_message = ( error_dict[fields.EVENT_RECORD_SNS_ATTRIBUTES_ERROR_MESSAGE]) str_timestamp = record[fields.EVENT_RECORD_SNS_TIMESTAMP] error_timestamp = datetime.datetime.strptime( str_timestamp, const.TIMESTAMP_TEMPLATE) common_config.logger.debug('Parsed error message: %s', error_message) save_to_vo_sync_errors(order_dict, error_message, error_timestamp) def handle_all_records(records): """Process all sns messages. Args: records (list): records part of message data """ for record in records: try: handle_record(record[fields.EVENT_RECORD_SNS]) except KeyError as e: sentry.sentry_client.captureMessage( '{} key doesn\'t exist in the record'.format(e), extra=record, stack=True) @exceptions.sentry_capture_exception def handler(event, context): """Lambda main function.""" handle_all_records(event[fields.EVENT_RECORDS])