Added further error handling and retries when sending a notification
All checks were successful
Build & Publish to GHCR / build (push) Successful in 27s

This commit is contained in:
florian 2025-10-11 21:50:22 +02:00
parent 7fc851e936
commit cd759f43a8

View File

@ -1,12 +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(title:str,chapter:int, link:str):
def send_notification(title:str,
chapter:int,
link:str,
max_retries: int = 5,
timeout: int = 5
):
headers = { headers = {
"X-API-Key-Internal": api_key, "X-API-Key-Internal": api_key,
"Content-Type": "application/json" "Content-Type": "application/json"
@ -20,16 +31,24 @@ def send_notification(title:str,chapter:int, link:str):
"link": link "link": link
}} }}
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)}")