"""Lambda function module for create_ingestion_lock.""" import boto3 from botocore.exceptions import ClientError from common.schemas.state_machine_schema import StateMachineSchema import config from src.exceptions import LockfileExistsException logger = config.app_logger s3_client = boto3.client('s3') def handler(event, context): """Create ingestion lock file.""" logger.info(f'Triggered create_ingestion_lock: {event}') sm_context = StateMachineSchema().load(event) upc = sm_context.product.upc lockfile_key = f'{config.INGESTION_LOCK_S3_PATH}{upc}.lock' # Check if lockfile exists try: logger.info('Checking if lock exists') s3_client.head_object( Bucket=config.INGESTION_LOCK_S3_BUCKET, Key=lockfile_key, ExpectedBucketOwner=config.INGESTION_S3_EXPECTED_OWNER) msg = f'Lockfile exists: {lockfile_key}' logger.warn(msg) raise LockfileExistsException(msg) except ClientError: # Lockfile does not exist logger.info(f'Creating lockfile: {lockfile_key}') s3_client.put_object( Bucket=config.INGESTION_LOCK_S3_BUCKET, Key=lockfile_key, ExpectedBucketOwner=config.INGESTION_S3_EXPECTED_OWNER ) return StateMachineSchema().dump(sm_context)