"""Lambda function module.""" import uuid from typing import Dict, Optional from ddex_ingester_common.helpers.s3_ddex import load_ddex_json from ddex_ingester_common.logging import utils as logging_utils from ddex_ingester_common.models.s3.body import Body as S3Context from ddex_ingester_common.models.state_machine.body import \ Body as StateMachineContext from ddex_ingester_common.schemas.s3_schema import S3Schema from ddex_ingester_common.schemas.state_machine_schema import \ StateMachineSchema from lambdacommon.graphql import graphql import config from config import graphql_gateway from constants import queries logger = logging_utils.get_logger(config.app_logger) def handler(event, context): """Lambda entry point.""" logger.info(f'Triggered ddex-ingester-create-video: {event}') s3_context = S3Schema().load(load_ddex_json(event)) context = StateMachineSchema().load(event) correlation_id = context.correlation_id or str(uuid.uuid4()) context.correlation_id = correlation_id logging_utils.update_logger_correlation_id(logger, correlation_id) logging_utils.update_logger_with_message_ids( logger, s3_context.message_id, s3_context.message_thread_id, s3_context.execution_name ) graphql_gateway.set_headers( { 'Orchard-User-Id': config.OA_USER, 'Correlation-Id': correlation_id, } ) create_video(context, s3_context) return StateMachineSchema().dump(context) def create_video( context: StateMachineContext, s3_context: S3Context) -> Optional[Dict]: """Create a video for the given UPC if it doesn't exist.""" upc = context.product.upc if upc: product_result = graphql_gateway.execute( queries.check_product_upc_exists, {'upc': upc} )['data']['productByUpc'] logger.info(f'Check if product exists: {product_result}') if product_result: return None payload = { 'create': { 'upc': upc, 'accountId': context.product.vendor_id, 'subaccountId': context.product.subaccount_id, 'projectId': str(context.project_id), 'typeOfVideo': s3_context.video.video_type, 'isrc': s3_context.video.isrc, 'notForDistribution': context.product.not_for_distribution, } } logger.info(f'Creating video with payload: {payload}') result = graphql_gateway.execute( queries.save_video_single_product, {'data': payload} )['data']['saveVideoSingleProduct'] if not upc: context.product.upc = result['upc'] return result def get_error_message(err: graphql.GraphQLError) -> str: """Retrieve error message body from GraphQL error.""" logger.info(f'Reading error message from: {str(err)}') return str(err)