Added further error handling and retries when sending a notification

This commit is contained in:
florian 2025-10-11 20:53:51 +02:00
parent db70de7659
commit dc9310e5d4

View File

@ -1,14 +1,23 @@
import requests import requests
from requests.exceptions import RequestException, Timeout, ConnectionError, HTTPError from requests.exceptions import RequestException, Timeout, ConnectionError, HTTPError
from fastapi import HTTPException
from secret_handler import return_credentials from secret_handler import return_credentials
import os import os
import time
import logging
backend_api_url=os.getenv("BACKEND_API_URL","localhost:8101/internal/receive-notifications") backend_api_url=os.getenv("BACKEND_API_URL","localhost:8101/internal/receive-notifications")
api_key= return_credentials("/etc/secrets/api_key") 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 = { headers = {
"X-API-Key-Internal": backend_api_url, "X-API-Key-Internal": api_key,
"Content-Type": "application/json" "Content-Type": "application/json"
} }
@ -20,16 +29,25 @@ def send_notification(notification:str)->str:
"link": None "link": None
}} }}
try: with requests.Session() as session:
response = requests.post(backend_api_url, headers=headers, json=data) for attempt in range(1,max_retries+1):
response.raise_for_status() try:
print("Success: Notification sent") 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: except (Timeout,ConnectionError) as e:
print("Error: request timed out") logger.warning(f"Attempt {attempt}/{max_retries} failed: {type(e).__name__}")
except ConnectionError: if attempt == max_retries:
print("Error: connection failed") raise HTTPException(status_code=503, detail=f"Notification service unavailable: {type(e).__name__}")
except HTTPError as e: time.sleep(2 ** (attempt - 1))
print(f"HTTP error: {e.response.status_code} - {e.response.text}")
except RequestException as e: except HTTPError as e:
print("Request failed:", str(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 ""