service-docker-repository-q.../src/send_notification.py
Florian 7d9efdbc28
All checks were successful
/ build (push) Successful in 39s
Correct notfication format
2025-10-18 21:27:06 +02:00

65 lines
2.2 KiB
Python

import requests
from requests.exceptions import RequestException, Timeout, ConnectionError, HTTPError
from fastapi import HTTPException
from secret_handler import return_credentials
import os
import time
from logger_handler import setup_logger
backend_api_url=os.getenv("BACKEND_API_URL","localhost:8101/internal/receive-notifications")
api_key= return_credentials("/etc/secrets/api_key")
logger = setup_logger(__name__)
def send_notification(notification:str,max_retries: int = 5,timeout: int = 5)->str:
"""
Sends a notification to the internal backend service when a new docker image is released.
Parameters:
notification: Name of the docker repository.
"""
headers = {
"X-API-Key-Internal": api_key,
"Content-Type": "application/json"
}
data = {
"receipent_user_id": 1,
"message": {
"title": notification,
"body": "A new version is available.",
"link": None,
"category":"utility",
"timestamp": int(time.time())
}}
logger.debug(f"[Notify] Preparing to send notification: title='{notification}'")
with requests.Session() as session:
for attempt in range(1, max_retries + 1):
try:
logger.debug(f"[Notify] Sending request to backend (attempt {attempt}/{max_retries})")
response = session.post(backend_api_url, headers=headers, json=data, timeout=timeout)
response.raise_for_status()
logger.info(f"[Notify] Notification sent successfully for '{notification}'")
return response.text
except (Timeout, ConnectionError) as e:
logger.warning(f"[Notify] Attempt {attempt}/{max_retries} failed: {type(e).__name__}")
if attempt == max_retries:
logger.error(f"[Notify] All retry attempts failed for '{notification}'")
raise HTTPException(status_code=503, detail=f"Notification service unavailable: {type(e).__name__}")
sleep_time = 2 ** (attempt - 1)
logger.debug(f"[Notify] Retrying in {sleep_time} seconds...")
time.sleep(sleep_time)
except HTTPError as e:
logger.error(f"[Notify] 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"[Notify] Unexpected request failure: {e}")
raise HTTPException(status_code=500, detail=f"Request failed: {str(e)}")