""" Background webhook delivery job execution. This module handles the execution of webhook deliveries in background threads, updating delivery logs and handling errors. """ import logging from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from web.services.webhook_service import WebhookService logger = logging.getLogger(__name__) def execute_webhook_delivery(webhook_id: int, alert_id: int, db_url: str): """ Execute a webhook delivery in the background. This function is designed to run in a background thread via APScheduler. It creates its own database session to avoid conflicts with the main application thread. Args: webhook_id: ID of the webhook to deliver alert_id: ID of the alert to send db_url: Database connection URL Workflow: 1. Create new database session for this thread 2. Call WebhookService to deliver webhook 3. WebhookService handles retry logic and logging 4. Close session """ logger.info(f"Starting background webhook delivery: webhook_id={webhook_id}, alert_id={alert_id}") # Create new database session for this thread engine = create_engine(db_url, echo=False) Session = sessionmaker(bind=engine) session = Session() try: # Create webhook service and deliver webhook_service = WebhookService(session) success = webhook_service.deliver_webhook(webhook_id, alert_id) if success: logger.info(f"Webhook {webhook_id} delivered successfully for alert {alert_id}") else: logger.warning(f"Webhook {webhook_id} delivery failed for alert {alert_id}") except Exception as e: logger.error(f"Error during webhook delivery: {e}", exc_info=True) finally: session.close() engine.dispose() logger.info(f"Webhook delivery job completed: webhook_id={webhook_id}, alert_id={alert_id}")