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
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
}}
with requests.Session() as session:
for attempt in range(1,max_retries+1):
try:
response = requests.post(backend_api_url, headers=headers, json=data)
response = session.post(backend_api_url, headers=headers, json=data, timeout=timeout)
response.raise_for_status()
print("Success: Notification sent")
logger.info("Notification sent successfully")
return response.text
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 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}")
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:
print("Request failed:", str(e))
logger.error(f"Unexpected request failure: {e}")
raise HTTPException(status_code=500, detail=f"Request failed: {str(e)}")
return ""