"""Lambda subscription-preference-sforce-updates function module.""" import logging import sentry_sdk import config from lambdacommon.common_config import logger from sentry_sdk import capture_exception from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration from sentry_sdk.integrations.logging import LoggingIntegration from src.connectors.kafka_producer import produce_for_id from src.logic.msg_handlers import read_source_event from src.logic.msg_handlers import get_operation_type from src.logic.msg_handlers import prepare_message MISSING_FAN_ID_MESSAGE = 'Message ignored for lack of `crmId` value.' MISSING_SUBSCRIPTION_ID_MESSAGE = 'Message ignored for lack of `updatedSubscriptions.crmId` value.' INVALID_OPERATION_MESSAGE = 'Message ignored due to it not containing an UPDATE operation' SUCCESS_MESSAGE = 'Successfully sent {operation} message for subscription crmId:{crm_id}' ERROR_GENERIC_MESSAGE = 'Something is wrong: {error}' logging_integration = LoggingIntegration( level=logging.INFO, event_level=logging.CRITICAL ) sentry_sdk.init( config.SENTRY_DSN, integrations=[AwsLambdaIntegration(), logging_integration] ) def handler(event, context): """Lambda entry point.""" try: msk_event = read_source_event(event) except Exception as e: logger.error(str(e)) capture_exception(e) return { 'status': 'ERROR', 'message': ERROR_GENERIC_MESSAGE.format(error=e) } crm_id = msk_event.get('crmId') if not crm_id: logger.warning(MISSING_FAN_ID_MESSAGE) return {'status': 'IGNORED', 'message': MISSING_FAN_ID_MESSAGE} operation = get_operation_type(msk_event) if not operation: logger.warning(INVALID_OPERATION_MESSAGE) return {'status': 'IGNORED', 'message': INVALID_OPERATION_MESSAGE} subscriptions = msk_event.get('updatedSubscriptions', []) success = [] for each_subs in subscriptions: subscription_crmid = each_subs.get('crmId') if not subscription_crmid: logger.warning(MISSING_SUBSCRIPTION_ID_MESSAGE, each_subs) continue try: message = prepare_message(each_subs, crm_id).to_dict() # Send Update to Kafka topic produce_for_id(message, subscription_crmid) success.append(subscription_crmid) logger.info(SUCCESS_MESSAGE.format(operation=operation, crm_id=subscription_crmid)) except Exception as e: logger.error(str(e)) capture_exception(e) # continue with other subscriptions, dont raise error. return { 'status': 'OK', 'successful_subscription_crmids': success, }