"""Lambda adjustment_file_process_batch function module.""" from __future__ import annotations from datetime import datetime from typing import Any, Mapping import sentry_sdk from lambdacommon.common_config import logger from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration import config from src.connectors.db import mysql_connection from src.connectors.repository import Repository from src.errors import ( PermanentError, TransientError, ) from src.processor import AdjustmentFileProcessBatchProcessor if config.SENTRY_DSN: sentry_sdk.init( dsn=config.SENTRY_DSN, environment=config.ENVIRONMENT, integrations=[AwsLambdaIntegration(timeout_warning=True)], ) def handler(event: Mapping[str, Any] | None, context: Any) -> dict[str, Any]: """Lambda entry point. Args: event: Event data passed to the Lambda function. context: Lambda runtime information. Raises: TransientError: Retriable errors (e.g., DB connection, S3 throttling). PermanentError: Non-retriable errors (e.g., validation, logic errors). Exception: For unexpected critical failures. """ try: logger.info(f'Function ARN: {context.invoked_function_arn}') logger.info('Establishing connections') with ( mysql_connection(**config.MYSQL_CONFIG) as mysql_conn, ): try: repository = Repository(mysql_conn) logger.info('Processing') start_time = datetime.now() processor = AdjustmentFileProcessBatchProcessor( repository=repository, ) result = processor.process(event) mysql_conn.commit() end_time = datetime.now() # Log processing time diff = end_time - start_time logger.info(f'Finished processing in {diff}') # Return result return result except Exception: mysql_conn.rollback() raise except TransientError as e: # Retriable errors (DB connection, IntegrityError, etc) logger.warning(f'Transient error encountered: {e}') raise TransientError(str(e)) from e except PermanentError as e: # Non-retriable errors (validation failures, not found, etc) logger.error(f'Permanent error encountered: {e}') raise PermanentError(str(e)) from e except Exception as e: # Unexpected errors logger.exception(f'Unexpected error encountered: {e}') raise