"""Lambda copy_asset function module.""" from typing import Any import httpx import ows_assets_uploader from common.connectors import graphql from common.connectors.exceptions import NetworkException from common.schemas.asset_copy import CopyAssetEvent from common.schemas.ingestion import Event from lambdacommon.common_config import logger from pydantic import ValidationError import config from src.constants import AssetNotFound from src.ingest_app import handle_ingest_event from src.utils import jitter def handle(event: CopyAssetEvent) -> CopyAssetEvent: """ Handle copy asset event. Args: copy_asset_event: Copy asset event payload. """ graphql.init_graphql_client( environment=config.ENVIRONMENT, service_name=config.M2M_APPLICATION_NAME, graphql_service_name=config.GRAPHQL_SERVICE_NAME, identity_id=config.IDENTITY_ID, profile_id=config.PROFILE_ID, profile_type=config.PROFILE_TYPE, headers={ "Correlation-Id": event.correlation_id, "Orchard-Roles": config.ROLE, }, ) asset = graphql.get_bulk_session_asset_file( bulk_session_id=str(event.bulk_session_id), original_filename=event.asset.source_filename, ) if not asset: logger.info( f"Session {event.bulk_session_id} has no key for file {event.asset.source_filename}" ) raise AssetNotFound() jitter() logger.info(f"Start asset upload. Source: {event.asset.source_file_location}") try: ows_assets_uploader.upload( **event.asset.model_dump(), asset_upload_type="stereo" if event.asset.track_id else "static_artwork", ) except httpx.HTTPStatusError as exc: status = exc.response.status_code if status == 429: raise NetworkException("ows-assets rate limit exceeded", child=exc) from exc if status in [502, 503, 504]: raise NetworkException( f"ows-assets error with status {status} encountered.", child=exc, ) from exc raise exc return event def handler(event_data: dict[str, Any], context: Any) -> dict[str, Any]: """ Lambda entry point. Args: event_data: Lambda event payload (should look like event.shadow.json) context: Lambda context. """ try: # Attempt to parse event_data as legacy Event first. legacy_event = Event(**event_data) track_data = event_data.get("track") or {} new_filename = handle_ingest_event( product=legacy_event.product_info.product, bulk_session_id=legacy_event.bulk_session_id, correlation_id=legacy_event.correlation_id, track_data=track_data, identity_uuid=legacy_event.identity_uuid, ) if event_data["product_info"]["product"]["artwork"]: event_data["product_info"]["product"]["artwork"]["ows_assets_filename"] = ( new_filename ) return event_data except ValidationError: # If parsing as legacy Event fails, attempt to parse event_data as new CopyAssetEvent. event = CopyAssetEvent(**event_data) return handle(event).model_dump(mode="json")