"""Lambda prepare_metadata function module.""" from typing import Any from common.connectors import s3 from common.connectors.graphql import GraphQLException from common.connectors.graphql import obo_graphql as graphql from common.schemas.ingestion import BulkEvent from common.schemas.s3_reference import S3Reference from lambdacommon.common_config import logger import config from src.exceptions import HydrationException, PrepareMetadataException def handle(event: BulkEvent, correlation_id: str, identity_uuid: str) -> BulkEvent: """ The main handler function, initiates a remote hydration call for the passed file and returns an updated bulk event. Args: event: BulkEvent containing bucket/key for the metadata json file to hydrate. correlation_id: Correlation ID for tracking identity_uuid: UUID of user for impersonation Returns: S3Reference: reference object associated with the updated metadata json file. Raises: HydrationException: if the hydration has failed due to the invalid data in the income file. PrepareMetadataException: if a general error occurs (file absence, network issues, etc). """ graphql.init_graphql_client( environment=config.ENVIRONMENT, service_name=config.M2M_APPLICATION_NAME, graphql_service_name=config.GRAPHQL_SERVICE_NAME, identity_id=identity_uuid, profile_id=config.PROFILE_ID, profile_type=config.PROFILE_TYPE, headers={ "Correlation-Id": correlation_id, "Orchard-Roles": config.ROLE, }, ) s3_filename = event.key assert event.execution_arn try: result = graphql.hydrate_metadata_json( s3_filename=s3_filename, execution_arn=event.execution_arn ) logger.info( f"Hydrate metadata_json mutation has returned {result.model_dump()} for the input '{s3_filename}'." ) except GraphQLException as ex: logger.error( f"Hydrate metadata_json mutation has failed for the input '{s3_filename}'." f"\nError: {ex.dict()}" ) if "metadata_hydration_error" in str(ex): raise HydrationException from ex raise return event def handler(event_data: dict[str, Any], context: Any) -> dict[str, Any]: """ Lambda entry point. Args: event_data: Lambda event payload context: Lambda context. """ s3_reference: S3Reference = S3Reference(**event_data) if not s3.object_exists(s3_reference): message = f"File {s3_reference.model_dump()} does not exist." logger.error(message) raise PrepareMetadataException(message) event = BulkEvent(**event_data) correlation_id = event.correlation_id identity_uuid = event.identity_uuid return handle(event, correlation_id, identity_uuid).model_dump()