"""Lambda function module.""" import json from constants import common import common_config from constants import general from constants import statuses import dynamodb import sentry def prepare_dynamodb_item(event, s3_event, attachment_attrs): """Prepare item suitable for DynamoDB table. Args: event (dict): original SNS event s3_event (dict): original S3 event attachment_attrs (dict): parsed attachment attributes Returns: dict: item suitable for DynamoDB """ s3_object = s3_event['Records'][0]['s3']['object'] s3_bucket = s3_event['Records'][0]['s3']['bucket'] key = s3_object.get('key') principal_id = s3_event['Records'][0]['userIdentity']['principalId'] status = statuses.STATUS_FAIL principalId_status = '{}_{}'.format(principal_id, status) item = { 'principalId_status': principalId_status, 'file_key': key, 'file_name': attachment_attrs.get('filename', key), 'etag': s3_object['eTag'], 'file_version': s3_object.get('versionId', 'No versionId.'), 'file_size': s3_object['size'], 'bucket_name': s3_bucket['name'], 'principalId': principal_id, 'status': status, 'message': event, 'event_time': s3_event['Records'][0]['eventTime'], 'ttl': dynamodb.get_ttl_value_for_item( general.DYNAMODB_ERROR_RECORD_TTL), } return item @sentry.sentry_capture_exception def handler(event, context): """Lambda entry point.""" if common_config.IGNORE_ALL_EVENTS is not None: common_config.logger.warning(common.IGNORE_MESSAGE) return common_config.logger.info('Starting to process SNS message') message = json.loads(event['Records'][0]['Sns']['Message']) s3_event = message.get('s3_event') # event by DLQ, ignore it if s3_event is None: common_config.logger.info('Ignoring DLQ event.') return attachment_attrs = message.get('attachment_attrs') item = prepare_dynamodb_item(event, s3_event, attachment_attrs) common_config.logger.info('Storing item in dynamodb.') dynamodb.put_item(common_config.DYNAMODB_TABLE_ERROR, item) common_config.logger.info('Done.')