From dc9310e5d4d44b6a6e6c27261d1ec461f2e4f468 Mon Sep 17 00:00:00 2001 From: florian Date: Sat, 11 Oct 2025 20:53:51 +0200 Subject: [PATCH] Added further error handling and retries when sending a notification --- src/send_notification.py | 46 ++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/src/send_notification.py b/src/send_notification.py index 0df0d1e..e8c7cbb 100644 --- a/src/send_notification.py +++ b/src/send_notification.py @@ -1,14 +1,23 @@ import requests from requests.exceptions import RequestException, Timeout, ConnectionError, HTTPError +from fastapi import HTTPException from secret_handler import return_credentials import os +import time +import logging + backend_api_url=os.getenv("BACKEND_API_URL","localhost:8101/internal/receive-notifications") api_key= return_credentials("/etc/secrets/api_key") +logger = logging.getLogger(__name__) -def send_notification(notification:str)->str: + +def send_notification(notification:str, + max_retries: int = 5, + timeout: int = 5 + )->str: headers = { - "X-API-Key-Internal": backend_api_url, + "X-API-Key-Internal": api_key, "Content-Type": "application/json" } @@ -20,16 +29,25 @@ def send_notification(notification:str)->str: "link": None }} - try: - response = requests.post(backend_api_url, headers=headers, json=data) - response.raise_for_status() - print("Success: Notification sent") + with requests.Session() as session: + for attempt in range(1,max_retries+1): + try: + response = session.post(backend_api_url, headers=headers, json=data, timeout=timeout) + response.raise_for_status() + logger.info("Notification sent successfully") + return response.text - except Timeout: - print("Error: request timed out") - except ConnectionError: - print("Error: connection failed") - except HTTPError as e: - print(f"HTTP error: {e.response.status_code} - {e.response.text}") - except RequestException as e: - print("Request failed:", str(e)) \ No newline at end of file + except (Timeout,ConnectionError) as e: + logger.warning(f"Attempt {attempt}/{max_retries} failed: {type(e).__name__}") + if attempt == max_retries: + raise HTTPException(status_code=503, detail=f"Notification service unavailable: {type(e).__name__}") + time.sleep(2 ** (attempt - 1)) + + except HTTPError as e: + logger.error(f"HTTP {e.response.status_code}: {e.response.text}") + raise HTTPException(status_code=e.response.status_code, detail=e.response.text) + + except RequestException as e: + logger.error(f"Unexpected request failure: {e}") + raise HTTPException(status_code=500, detail=f"Request failed: {str(e)}") + return "" \ No newline at end of file