"""Lambda function module.""" from src.config import logger from constants import general from constants import errors from src import buffers_utils from src import image_validation_logic from src import lambda_exceptions from src import s3 from src import status def handler(event, context): """Lambda entry point.""" allocated_buffers = None bucket = event['bucket'] key = event['key'] asset_upload_type = event['asset_upload_type'] input_params = { 'key': key, 'bucket': bucket, 'asset_upload_type': asset_upload_type } head_object_response = s3.head_object(bucket, key) if not head_object_response: lambda_exceptions.notify_and_raise( general.LAMBDA_NAME, general.IMAGE_VALIDATION_ERROR_STATUS, errors.S3_FILE_NOT_FOUND_CODE, key, bucket, { 'key': key, 'bucket': bucket}, input_params.copy()) try: if asset_upload_type != general.ASSET_UPLOAD_STATIC_ARTWORK: lambda_exceptions.notify_and_raise( general.LAMBDA_NAME, general.IMAGE_VALIDATION_ERROR_STATUS, errors.IMAGE_WRONG_ASSET_UPLOAD_TYPE_ERROR_CODE, key, bucket, { 'key': key, 'bucket': bucket, 'type': asset_upload_type}, input_params.copy()) allocated_buffers = buffers_utils.allocate_buffers(1) buffer = allocated_buffers[0] s3.download_file_object(bucket, key, buffer) image_validation_logic.validate_image( file_contents=buffer ) status.send_general_status( general.LAMBDA_NAME, general.IMAGE_VALIDATION_COMPLETE_STATUS, key, input_params=input_params.copy(), bucket=bucket) return { **input_params, 'is_valid': True, } except lambda_exceptions.LoggedException: raise except image_validation_logic.InvalidImageError as iie: status.send_general_status( function=general.LAMBDA_NAME, status=general.IMAGE_VALIDATION_ERROR_STATUS, filename=key, error_code=iie.code, description=str(iie), input_params=input_params.copy() ) return {'is_valid': False} except Exception as e: logger.exception(str(e)) lambda_exceptions.notify_and_raise( general.LAMBDA_NAME, general.IMAGE_VALIDATION_ERROR_STATUS, errors.IMAGE_VALIDATION_ERROR_CODE, key, bucket, { 'message': str(e)}, input_params) finally: if allocated_buffers: buffers_utils.release_allocated_buffers(allocated_buffers)