"""Utility functions for AWS Lambda interactions.""" import json from typing import Any, Dict import boto3 from botocore.exceptions import ClientError from oto import status from collaborator.utils.error import OwsError def invoke_lambda( function_name: str, payload: Dict[str, Any], ) -> Dict[str, Any]: """Invoke an AWS Lambda function. Args: function_name: Name or ARN of the Lambda function payload: Dictionary payload to send to the Lambda function Returns: Dictionary containing the Lambda function response payload """ client = boto3.client("lambda") try: response = client.invoke( FunctionName=function_name, InvocationType="RequestResponse", Payload=json.dumps(payload), ) except ClientError as error: error_response = error.response error_code = error_response.get("Error", {}).get("Code") error_msg = error_response.get("Error", {}).get("Message") status_code = error_response.get("ResponseMetadata", {}).get("HTTPStatusCode") raise OwsError( message=f"{error_code}: {error_msg}", status=status_code or status.INTERNAL_ERROR, ) from error if response.get("FunctionError"): response_payload = response.get("Payload") if response_payload: error_response = json.load(response_payload) error_message = error_response.get("errorMessage", "Unknown error") else: error_message = "Unknown error" raise OwsError( message=f"Lambda function error: {error_message}", status=status.INTERNAL_ERROR, ) # Parse and return the response payload response_payload = response.get("Payload") if response_payload: return json.load(response_payload) return {}