import logging.config from typing import Any import sentry_sdk from pydantic import ValidationError from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration from sentry_sdk.integrations.httpx import HttpxIntegration from app.config import settings from app.handlers import ProcessSongwhipEventRequest, process_songwhip_event from app.schemas import KafkaEvent from app.types import PresaveEventValidator # Configure logging logging.config.dictConfig(settings.logging_config) # Setup Sentry if settings.sentry_dsn: sentry_sdk.init( dsn=settings.sentry_dsn, environment=settings.environment, integrations=[ AwsLambdaIntegration(), HttpxIntegration(), ], ) # Get the logger logger = logging.getLogger(__name__) def handle(event: Any, context: Any) -> dict[str, Any]: """Handle the event asynchronously.""" logger.info("Received event") # Validate the event kafka_event = KafkaEvent.model_validate(event) # Extract Songwhip events events = [] invalid_records = [] for records in kafka_event.records.values(): for record in records: try: events.append(PresaveEventValidator.validate_python(record.value)) except ValidationError as exc: invalid_records.append((record.value, exc.errors())) process_songwhip_event(ProcessSongwhipEventRequest(events=events)) if invalid_records: logger.error( "Failed to handle Songwhip events due to invalid records", extra={ "invalid_records": [ {"value": value, "errors": errors} for value, errors in invalid_records ] }, ) return {"status": "OK"}