Added further error handling and retries when sending a notification
All checks were successful
Build & Publish to GHCR / build (push) Successful in 27s
All checks were successful
Build & Publish to GHCR / build (push) Successful in 27s
This commit is contained in:
parent
7fc851e936
commit
cd759f43a8
@ -1,12 +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(title:str,chapter:int, link:str):
|
||||
|
||||
def send_notification(title:str,
|
||||
chapter:int,
|
||||
link:str,
|
||||
max_retries: int = 5,
|
||||
timeout: int = 5
|
||||
):
|
||||
headers = {
|
||||
"X-API-Key-Internal": api_key,
|
||||
"Content-Type": "application/json"
|
||||
@ -20,16 +31,24 @@ def send_notification(title:str,chapter:int, link:str):
|
||||
"link": link
|
||||
}}
|
||||
|
||||
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))
|
||||
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)}")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user